<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://nleo.me/feed.xml" rel="self" type="application/atom+xml" /><link href="https://nleo.me/" rel="alternate" type="text/html" /><updated>2026-01-12T07:10:14+00:00</updated><id>https://nleo.me/feed.xml</id><title type="html">nLeo.me</title><subtitle></subtitle><author><name>Leo</name><email>mail@nleo.me</email></author><entry><title type="html">AMQP1.0 over WebSocket in Python</title><link href="https://nleo.me/en/2026/01/09/Python_amqp10ws.html" rel="alternate" type="text/html" title="AMQP1.0 over WebSocket in Python" /><published>2026-01-09T10:52:21+00:00</published><updated>2026-01-09T10:52:21+00:00</updated><id>https://nleo.me/en/2026/01/09/Python_amqp10ws</id><content type="html" xml:base="https://nleo.me/en/2026/01/09/Python_amqp10ws.html"><![CDATA[<h1 id="investigation-of-python-qpid-proton">Investigation of Python Qpid Proton</h1>

<h2 id="background">Background</h2>

<p>We aim to integrate <strong>SAP Event Mesh</strong> with <strong>AMQP 1.0 over WebSocket (amqp10ws)</strong> in Python applications. This transport differs from native <strong>AMQP 1.0 (amqp10)</strong> primarily at the transport layer: the former runs over <strong>WebSocket</strong>, while the latter relies on <strong>raw TCP</strong>.</p>

<p>In the Python ecosystem, there are two commonly referenced AMQP 1.0 client libraries:</p>

<ul>
  <li><strong>Apache Qpid Proton</strong></li>
  <li><strong>Azure uAMQP</strong></li>
</ul>

<p>However, <strong>uAMQP has been officially deprecated and unmaintained since 2025 Q1</strong>, leaving <strong>Qpid Proton</strong> as the only viable long-term option. This raises the question of whether Qpid Proton can support AMQP 1.0 over WebSocket.</p>

<hr />

<h2 id="problem-definition">Problem Definition</h2>

<p>Because <strong>amqp10ws uses a fundamentally different connection establishment mechanism than amqp10</strong>, the first and most critical issue is understanding <strong>how the client connects and authenticates</strong> against SAP Event Mesh.</p>

<p>Specifically:</p>

<ul>
  <li>Does Python Qpid Proton natively support WebSocket (<code class="language-plaintext highlighter-rouge">ws://</code>, <code class="language-plaintext highlighter-rouge">wss://</code>)?</li>
  <li>If not, what would be required to implement AMQP 1.0 over WebSocket in Python?</li>
</ul>

<hr />

<h2 id="analysis">Analysis</h2>

<h3 id="sap-reference-implementation">SAP Reference Implementation</h3>

<p>We first examined SAP’s official Node.js implementation:<br />
<code class="language-plaintext highlighter-rouge">@sap/xb-msg-amqp-v100</code>.</p>

<p>According to SAP CAP documentation, there are two Event Mesh integration modes:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">enterprise-messaging</code></li>
  <li><code class="language-plaintext highlighter-rouge">enterprise-messaging-shared</code></li>
</ul>

<p>From the source code, the distinction becomes explicit:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="dl">"</span><span class="s2">enterprise-messaging</span><span class="dl">"</span><span class="p">:</span> <span class="p">{</span>
  <span class="nl">kind</span><span class="p">:</span> <span class="dl">"</span><span class="s2">enterprise-messaging-http</span><span class="dl">"</span><span class="p">,</span>
<span class="p">},</span>
<span class="dl">"</span><span class="s2">enterprise-messaging-shared</span><span class="dl">"</span><span class="p">:</span> <span class="p">{</span> <span class="c1">// temporary compatibility</span>
  <span class="nl">kind</span><span class="p">:</span> <span class="dl">"</span><span class="s2">enterprise-messaging-amqp</span><span class="dl">"</span><span class="p">,</span>
<span class="p">},</span>
</code></pre></div></div>

<p>This indicates that <strong><code class="language-plaintext highlighter-rouge">enterprise-messaging</code> uses HTTP-based transport</strong>, while <strong><code class="language-plaintext highlighter-rouge">enterprise-messaging-shared</code> uses AMQP</strong>, which is relevant for amqp10ws.</p>

<hr />

<h3 id="how-does-enterprisemessagingshared-connect-to-the-broker">How Does <code class="language-plaintext highlighter-rouge">EnterpriseMessagingShared</code> Connect to the Broker?</h3>

<p>Examining <code class="language-plaintext highlighter-rouge">Client.connect</code> in <code class="language-plaintext highlighter-rouge">@sap/xb-msg-amqp-v100</code>, we see that the client explicitly supports:</p>

<ul>
  <li>Secured / unsecured TCP</li>
  <li>Secured / unsecured WebSocket</li>
</ul>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">tls</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">tcp</span><span class="p">.</span><span class="nx">tlsConnect</span><span class="p">(</span><span class="nx">options</span><span class="p">,</span> <span class="nx">init</span><span class="p">,</span> <span class="nx">fail</span><span class="p">);</span>
<span class="p">}</span> <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">net</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">tcp</span><span class="p">.</span><span class="nx">netConnect</span><span class="p">(</span><span class="nx">options</span><span class="p">,</span> <span class="nx">init</span><span class="p">,</span> <span class="nx">fail</span><span class="p">);</span>
<span class="p">}</span> <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">wss</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">if</span><span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">oa2</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">oa2</span><span class="p">.</span><span class="nx">runGrantFlow</span><span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">oa2</span><span class="p">,</span>
            <span class="p">(</span><span class="nx">headers</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="nx">ws</span><span class="p">.</span><span class="nx">tlsConnect</span><span class="p">(</span><span class="nx">options</span><span class="p">,</span> <span class="nx">headers</span><span class="p">,</span> <span class="nx">init</span><span class="p">,</span> <span class="nx">fail</span><span class="p">),</span>
            <span class="nx">fail</span>
        <span class="p">);</span>
    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
        <span class="nx">ws</span><span class="p">.</span><span class="nx">tlsConnect</span><span class="p">(</span><span class="nx">options</span><span class="p">,</span> <span class="p">{},</span> <span class="nx">init</span><span class="p">,</span> <span class="nx">fail</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span> <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">ws</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">if</span><span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">oa2</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">oa2</span><span class="p">.</span><span class="nx">runGrantFlow</span><span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">oa2</span><span class="p">,</span>
            <span class="p">(</span><span class="nx">headers</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="nx">ws</span><span class="p">.</span><span class="nx">netConnect</span><span class="p">(</span><span class="nx">options</span><span class="p">,</span> <span class="nx">headers</span><span class="p">,</span> <span class="nx">init</span><span class="p">,</span> <span class="nx">fail</span><span class="p">),</span>
            <span class="nx">fail</span>
        <span class="p">);</span>
    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
        <span class="nx">ws</span><span class="p">.</span><span class="nx">netConnect</span><span class="p">(</span><span class="nx">options</span><span class="p">,</span> <span class="p">{},</span> <span class="nx">init</span><span class="p">,</span> <span class="nx">fail</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="nx">fail</span><span class="p">(</span><span class="nx">ErrMsg</span><span class="p">(</span><span class="nx">EC</span><span class="p">.</span><span class="nx">CLIENT_MISS_DEST</span><span class="p">));</span>
<span class="p">}</span>
</code></pre></div></div>

<p>For <strong>SAP Event Mesh</strong>, the execution path is <code class="language-plaintext highlighter-rouge">wss + oa2</code>, which means the client must first retrieve an <strong>OAuth2 access token</strong> using the <strong>client credentials grant</strong>.</p>

<hr />

<h3 id="oauth2-grant-flow">OAuth2 Grant Flow</h3>

<p>The grant flow attempts header-based authentication first, falling back to URL parameters if necessary:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">runGrantFlow</span><span class="p">(</span><span class="nx">options</span><span class="p">,</span> <span class="nx">done</span><span class="p">,</span> <span class="nx">failed</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">secret</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">sendAuthViaHeader</span><span class="p">(</span><span class="nx">options</span><span class="p">,</span> <span class="nx">done</span><span class="p">,</span> <span class="p">(</span><span class="nx">error</span><span class="p">)</span> <span class="o">=&gt;</span>
            <span class="nx">sendAuthViaParams</span><span class="p">(</span><span class="nx">options</span><span class="p">,</span> <span class="nx">done</span><span class="p">,</span> <span class="nx">failed</span><span class="p">,</span> <span class="nx">error</span><span class="p">));</span>
    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
        <span class="nx">sendAuthViaParams</span><span class="p">(</span><span class="nx">options</span><span class="p">,</span> <span class="nx">done</span><span class="p">,</span> <span class="p">(</span><span class="nx">error</span><span class="p">)</span> <span class="o">=&gt;</span>
            <span class="nx">sendAuthViaHeader</span><span class="p">(</span><span class="nx">options</span><span class="p">,</span> <span class="nx">done</span><span class="p">,</span> <span class="nx">failed</span><span class="p">,</span> <span class="nx">error</span><span class="p">));</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Once the access token is obtained, it is injected into the <strong>WebSocket upgrade request headers</strong>.</p>

<hr />

<h3 id="websocket-upgrade-and-connection-establishment">WebSocket Upgrade and Connection Establishment</h3>

<p>After authentication, the client initiates an HTTP → WebSocket upgrade:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">tlsConnect</span><span class="p">(</span><span class="nx">options</span><span class="p">,</span> <span class="nx">headers</span><span class="p">,</span> <span class="nx">done</span><span class="p">,</span> <span class="nx">failed</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">connect</span><span class="p">(</span>
        <span class="nx">https</span><span class="p">.</span><span class="nx">request</span><span class="p">(</span><span class="nx">createUpgradeRequest</span><span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">wss</span><span class="p">,</span> <span class="nx">headers</span><span class="p">)),</span>
        <span class="nx">options</span><span class="p">,</span>
        <span class="nx">done</span><span class="p">,</span>
        <span class="nx">failed</span>
    <span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<p>If the upgrade succeeds, the TCP socket is wrapped as a WebSocket connection, and all subsequent traffic consists of <strong>binary AMQP frames over WebSocket</strong>:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">done</span><span class="p">(</span>
  <span class="k">new</span> <span class="nx">WsConnection</span><span class="p">(</span>
    <span class="nx">options</span><span class="p">,</span>
    <span class="nx">socket</span><span class="p">,</span>
    <span class="k">new</span> <span class="nx">WsReader</span><span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">tune</span><span class="p">,</span> <span class="kc">false</span><span class="p">),</span>
    <span class="k">new</span> <span class="nx">WsWriter</span><span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">tune</span><span class="p">,</span> <span class="nx">socket</span><span class="p">,</span> <span class="kc">true</span><span class="p">)</span>
  <span class="p">)</span>
<span class="p">);</span>
</code></pre></div></div>

<h3 id="transport-level-difference">Transport-Level Difference</h3>

<p>This confirms the essential difference between the two transports:</p>

<p><strong>Native AMQP 1.0</strong></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[IP] → [TCP] → [AMQP Frames]
</code></pre></div></div>

<p><strong>AMQP 1.0 over WebSocket</strong></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[HTTP Upgrade] → [WebSocket] → [AMQP Frames]
</code></pre></div></div>

<p>This behavior is fully aligned with the <strong>AMQP WebSocket Binding Specification</strong>:</p>

<blockquote>
  <p>The WebSocket Protocol connection MUST be opened as described in Section 4 of the WebSocket specification <strong>[RFC6455]</strong>. The initiating AMQP endpoint (the WebSocket Client) sends a HTTP GET request to the receiving AMQP endpoint (the WebSocket Server) identifying AMQP 1.0 as the subprotocol being used.</p>

  <p>…</p>

  <p>As per the WebSocket specification <strong>[RFC6455]</strong>, if the Server agrees to the WebSocket upgrade to the requested subprotocol then it MUST respond with an HTTP Status-Line with status code 101 (“Switching Protocols”) and echo the requested subprotocol in the Sec-WebSocket-Protocol HTTP header.</p>
</blockquote>

<hr />

<h2 id="does-python-qpid-proton-natively-support-websocket">Does Python Qpid Proton Natively Support WebSocket?</h2>

<p>The key question is whether Python Qpid Proton can establish such a WebSocket-based connection.</p>

<p>Looking at <code class="language-plaintext highlighter-rouge">Container.connect</code>, we see that connection handling is delegated to an internal <code class="language-plaintext highlighter-rouge">_Connector</code> handler:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">_connect</span><span class="p">(</span>
        <span class="bp">self</span><span class="p">,</span>
        <span class="n">url</span><span class="p">:</span> <span class="n">Optional</span><span class="p">[</span><span class="n">Union</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="n">Url</span><span class="p">]]</span> <span class="o">=</span> <span class="bp">None</span><span class="p">,</span>
        <span class="n">urls</span><span class="p">:</span> <span class="n">Optional</span><span class="p">[</span><span class="n">List</span><span class="p">[</span><span class="nb">str</span><span class="p">]]</span> <span class="o">=</span> <span class="bp">None</span><span class="p">,</span>
        <span class="n">handler</span><span class="p">:</span> <span class="n">Optional</span><span class="p">[</span><span class="s">'Handler'</span><span class="p">]</span> <span class="o">=</span> <span class="bp">None</span><span class="p">,</span>
        <span class="n">reconnect</span><span class="p">:</span> <span class="n">Optional</span><span class="p">[</span><span class="n">Union</span><span class="p">[</span><span class="n">List</span><span class="p">[</span><span class="n">Union</span><span class="p">[</span><span class="nb">float</span><span class="p">,</span> <span class="nb">int</span><span class="p">]],</span> <span class="nb">bool</span><span class="p">,</span> <span class="n">Backoff</span><span class="p">]]</span> <span class="o">=</span> <span class="bp">None</span><span class="p">,</span>
        <span class="n">heartbeat</span><span class="p">:</span> <span class="bp">None</span> <span class="o">=</span> <span class="bp">None</span><span class="p">,</span>
        <span class="n">ssl_domain</span><span class="p">:</span> <span class="n">Optional</span><span class="p">[</span><span class="n">SSLDomain</span><span class="p">]</span> <span class="o">=</span> <span class="bp">None</span><span class="p">,</span>
        <span class="o">**</span><span class="n">kwargs</span>
<span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Connection</span><span class="p">:</span>
  <span class="n">conn</span> <span class="o">=</span> <span class="bp">self</span><span class="p">.</span><span class="n">connection</span><span class="p">(</span><span class="n">handler</span><span class="p">)</span>
  <span class="p">...</span>
  <span class="n">connector</span> <span class="o">=</span> <span class="n">_Connector</span><span class="p">(</span><span class="n">conn</span><span class="p">)</span>
  <span class="p">...</span>
  <span class="n">conn</span><span class="p">.</span><span class="n">_overrides</span> <span class="o">=</span> <span class="n">connector</span>
  <span class="p">...</span>
  <span class="n">conn</span><span class="p">.</span><span class="nb">open</span><span class="p">()</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">_Connector</code> eventually binds the connection to a transport and dispatches a <code class="language-plaintext highlighter-rouge">CONNECTION_BOUND</code> event, which is handled by <code class="language-plaintext highlighter-rouge">IOHandler.on_connection_bound</code>.</p>

<hr />

<h3 id="transport-binding-in-qpid-proton">Transport Binding in Qpid Proton</h3>

<p>The relevant implementation in <code class="language-plaintext highlighter-rouge">IOHandler</code> is:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">on_connection_bound</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">event</span><span class="p">:</span> <span class="n">Event</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="bp">None</span><span class="p">:</span>
    <span class="p">...</span>
    <span class="n">addrs</span> <span class="o">=</span> <span class="n">socket</span><span class="p">.</span><span class="n">getaddrinfo</span><span class="p">(</span><span class="n">host</span><span class="p">,</span> <span class="n">port</span><span class="p">,</span> <span class="n">socket</span><span class="p">.</span><span class="n">AF_UNSPEC</span><span class="p">,</span> <span class="n">socket</span><span class="p">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span>
    <span class="n">sock</span> <span class="o">=</span> <span class="n">IO</span><span class="p">.</span><span class="n">connect</span><span class="p">(</span><span class="n">addrs</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
</code></pre></div></div>

<p>And the socket creation logic:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">IO</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="o">@</span><span class="nb">staticmethod</span>
    <span class="k">def</span> <span class="nf">connect</span><span class="p">(</span><span class="n">addr</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">socket</span><span class="p">.</span><span class="n">socket</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="p">.</span><span class="n">socket</span><span class="p">(</span><span class="n">addr</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">addr</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="n">addr</span><span class="p">[</span><span class="mi">2</span><span class="p">])</span>
        <span class="n">s</span><span class="p">.</span><span class="n">connect</span><span class="p">(</span><span class="n">addr</span><span class="p">[</span><span class="mi">4</span><span class="p">])</span>
        <span class="k">return</span> <span class="n">s</span>
</code></pre></div></div>

<p>This makes it explicit that:</p>

<ul>
  <li>Qpid Proton <strong>always uses raw TCP sockets</strong></li>
  <li>There is <strong>no HTTP handshake</strong></li>
  <li>There is <strong>no WebSocket framing</strong></li>
  <li>The URL scheme only affects <strong>TLS configuration (<code class="language-plaintext highlighter-rouge">amqp</code> vs <code class="language-plaintext highlighter-rouge">amqps</code>)</strong></li>
</ul>

<p>Therefore, <strong>WebSocket (<code class="language-plaintext highlighter-rouge">ws://</code>, <code class="language-plaintext highlighter-rouge">wss://</code>) is not natively supported</strong> by Python Qpid Proton.</p>

<hr />

<h2 id="how-can-amqp-10-over-websocket-be-achieved-in-python">How Can AMQP 1.0 over WebSocket Be Achieved in Python?</h2>

<p>Because <strong>Qpid Proton hardcodes TCP socket creation</strong> via <code class="language-plaintext highlighter-rouge">IOHandler</code> and <code class="language-plaintext highlighter-rouge">ConnectSelectable</code>, the default connection mechanism cannot be reused.</p>

<p>To support <strong>AMQP 1.0 over WebSocket</strong> in Python, the following steps are required:</p>

<ol>
  <li><strong>OAuth2 Token Retrieval</strong>
Authenticate against the <code class="language-plaintext highlighter-rouge">uaa</code> endpoint from the Event Mesh service key to obtain an <code class="language-plaintext highlighter-rouge">access_token</code>.</li>
  <li><strong>WebSocket Connection Establishment</strong>
Use a WebSocket client library (e.g. <code class="language-plaintext highlighter-rouge">websocket-client</code> or <code class="language-plaintext highlighter-rouge">websockets</code>) to connect to the <code class="language-plaintext highlighter-rouge">wss://</code> endpoint, injecting the <code class="language-plaintext highlighter-rouge">Authorization: Bearer &lt;token&gt;</code> header.</li>
  <li><strong>Manual Proton Transport Binding</strong>
Bind the WebSocket’s binary send/receive stream to a <code class="language-plaintext highlighter-rouge">proton.Transport</code> instance, effectively replacing Proton’s internal TCP-based I/O layer.</li>
</ol>

<p>This approach requires <strong>bypassing or re-implementing Proton’s I/O layer</strong>, which is non-trivial and explains why existing support is limited.</p>

<hr />

<h2 id="references">References</h2>

<ol>
  <li><a href="https://help.sap.com/docs/event-mesh/event-mesh/messaging-protocols-and-libraries">Messaging Protocols and Libraries</a></li>
  <li><a href="https://www.npmjs.com/package/@sap/xb-msg-amqp-v100">@sap/xb-msg-amqp-v100</a></li>
  <li><a href="https://cap.cloud.sap/docs/node.js/messaging#event-mesh-shared">SAP Event Mesh (Shared)</a></li>
  <li><a href="https://docs.oasis-open.org/amqp-bindmap/amqp-wsb/v1.0/cs01/amqp-wsb-v1.0-cs01.html">AMQP WebSocket Binding Specification</a></li>
</ol>]]></content><author><name>Leo</name><email>mail@nleo.me</email></author><category term="en" /><summary type="html"><![CDATA[Investigation of Python Qpid Proton]]></summary></entry><entry><title type="html">Analyze massive page 404 issue in PROD</title><link href="https://nleo.me/cn/2024/02/28/massive_404_prod_issue_analysis.html" rel="alternate" type="text/html" title="Analyze massive page 404 issue in PROD" /><published>2024-02-28T10:52:21+00:00</published><updated>2024-02-28T10:52:21+00:00</updated><id>https://nleo.me/cn/2024/02/28/massive_404_prod_issue_analysis</id><content type="html" xml:base="https://nleo.me/cn/2024/02/28/massive_404_prod_issue_analysis.html"><![CDATA[<p>上个周日我们收到大量线上告警，某个关键页面（后续我们以<code class="language-plaintext highlighter-rouge">/abc</code>代指）持续404，经过人工重启server之后临时解决了问题，不过这个问题的root cause还没有完全定位到，所以这里只是记录一下问题分析过程。</p>

<p><img src="/assets/images/posts/2024-02-28/1.png" alt="availibility" /></p>

<p>由于我们前端用的nextjs的dynamic route来生成页面，根据代码实现我们首先怀疑是由于后端API调用出错导致不能成功生成页面，从日志中我们确实发现在告警刚出现的时候有几个超时的请求，通过静态分析和本地重现证实这种情况会导致404，但随着而来的问题是：由于我们有设置revalidate，意味着下一次rebuild page如果能正常访问API就能自行修复404问题，而这些请求只有初期有过超时，后面基本上都是成功返回的，这是怎么回事？</p>

<p>我们先分析了后续请求的失败场景，发现它们都是返回了400状态码，根据日志我们发现后端显示某一个参数多了个<code class="language-plaintext highlighter-rouge">/</code>导致不能正常处理，但进一步分析我们发现这种类型的请求<code class="language-plaintext highlighter-rouge">/abc/</code>会被重定向到<code class="language-plaintext highlighter-rouge">/abc</code>，意味着虽然<code class="language-plaintext highlighter-rouge">/abc/</code>页面不会正常生成，但是用户会被自动重定向到正确生成的<code class="language-plaintext highlighter-rouge">/abc</code>页面，所以用户是感知不到这个404的，当然这里其实我们是应该对这个slug值做urlencoding处理的。
排除了后端API 400导致的页面无法生成的可能性之后，分析一度陷入僵局，因为这个页面的生成逻辑非常简单，只要能拿到后端的数据基本上就应该能成功返回props。我们意外的发现在告警的这段时间内，<code class="language-plaintext highlighter-rouge">/abc</code>返回200的count为1.6K+，而404的count为0.8K+，这意味着确实在后端API恢复正常之后大部分情况下<code class="language-plaintext highlighter-rouge">/abc</code>页面是成功返回的，同时这个2:1的比例引起我们注意，因为前端节点一共有3个，我们大胆假设有没有可能其中某一个节点出了问题？</p>

<p>图1是我们在监控系统中对service instance进行分组之后观察到的该页面404 metrics，每一种颜色代表一个instance，我们可以很明显的观察到在告警初期由于API timeout导致的404之后，只有一个instance还在持续404，另外两个已经恢复正常，从而证实了我们的猜想。</p>

<p><img src="/assets/images/posts/2024-02-28/2.png" alt="图2" /></p>

<p>锁定了这个instance之后，我们进一步查找了该节点向后端的API请求记录，结果发现从凌晨5点多之后，任何用户访问这个节点的<code class="language-plaintext highlighter-rouge">/abc</code>页面都未再触发API请求，也就是说nextjs一直返回缓存的404页面而没有revalidate，我们尝试着在本地重现这个问题，但遗憾的是并没有成功重现，不过也可以理解，毕竟另外两个节点也没有重现该节点的问题。</p>

<p>最后我们猜测是触发了nextjs 13的某个隐藏bug，虽然nextjs社区也有不少人反应revalidate not working的问题，但实际场景跟我们还是或多或少有不一样，所以这一问题暂时只能留下一个问号。</p>]]></content><author><name>Leo</name><email>mail@nleo.me</email></author><category term="cn" /><summary type="html"><![CDATA[上个周日我们收到大量线上告警，某个关键页面（后续我们以/abc代指）持续404，经过人工重启server之后临时解决了问题，不过这个问题的root cause还没有完全定位到，所以这里只是记录一下问题分析过程。]]></summary></entry><entry><title type="html">Dive into transaction timeout issue</title><link href="https://nleo.me/en/2023/09/07/dive_into_transaction_timeout_issue.html" rel="alternate" type="text/html" title="Dive into transaction timeout issue" /><published>2023-09-07T03:52:21+00:00</published><updated>2023-09-07T03:52:21+00:00</updated><id>https://nleo.me/en/2023/09/07/dive_into_transaction_timeout_issue</id><content type="html" xml:base="https://nleo.me/en/2023/09/07/dive_into_transaction_timeout_issue.html"><![CDATA[<p>Write DB record(s) concurrently or parallelly is a common situation, while it can easily result in defects which is hard to detect in PR review and often cause disasters in production. My previous blog mentioned a deadlock issue which is caused by such scenario, briefly speaking the root cause is that we are trying to update/delete same batch records parallelly in different order and locked in mutual finally.</p>

<p>Recently we received another production issue which says <code class="language-plaintext highlighter-rouge">transaction rolled back by lock wait timeout: Lock-wait time out exceeded [OWNER=152260476930, TYPE=RECORD_LOCK, CURRENT_MODE=NON_KEY_EXCLUSIVE, REQUESTED_MODE=NON_KEY_EXCLUSIVE], rc=4628</code>. Lock wait timeout is better than deadlock, to be honest, it often indicates that there is a long running transaction and locked table(s) or row(s) so that other transactions cannot write it, btw, we rarely see that read transaction is blocked since modern database often provide MVCC mechanism to guarantee consistency read, unless you choose to use locking read.</p>

<p>Let’s back to our topic, with a first glance at the error log and we can know lock owner transaction id , so first thing we did is to query history running statistics:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">_sys_statistics</span><span class="p">.</span><span class="n">host_blocked_transactions</span>
<span class="k">where</span> <span class="n">lock_owner_update_transaction_id</span> <span class="o">=</span> <span class="mi">152260476930</span>
</code></pre></div></div>

<p>And we get over one hundred locked transaction records, after investigated the result, we knew what the situation is: one user was trying to update the records several times while our job is holding the record lock, all of those updates finally failed with timeout.</p>

<p>Now the question is why our job is keeping the lock for over 30 mins(the default timeout in HANA)? We went to our job monitor tools and noticed our daily job took 49 mins to finish in that day, sounds like it’s clear? Definitely not, we did some optimization in the past to separate our DB operations in pages and each page takes one standalone transaction, that means even though the total job execution time is 49 mins, for each page it shouldn’t take so much time, at least shouldn’t over 30 mins, right? So we went to our code and check it again: (some unnecessary code omitted)</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="kd">let</span> <span class="nx">ptx</span> <span class="o">=</span> <span class="kc">undefined</span><span class="p">;</span>
  <span class="k">try</span> <span class="p">{</span>
    <span class="kd">const</span> <span class="nx">inactiveProgress</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">getAllInactiveProgress</span><span class="p">(</span><span class="nx">daysInactive</span><span class="p">);</span>
    <span class="kd">const</span> <span class="nx">total</span> <span class="o">=</span> <span class="nx">inactiveProgress</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span>
    <span class="k">do</span> <span class="p">{</span>
      <span class="nx">ptx</span> <span class="o">=</span> <span class="nx">cds</span><span class="p">.</span><span class="nx">tx</span><span class="p">();</span>
      <span class="nx">page</span> <span class="o">=</span> <span class="nx">pagination</span><span class="p">.</span><span class="nx">getPage</span><span class="p">(</span><span class="nx">inactiveProgress</span><span class="p">,</span> <span class="nx">offset</span><span class="p">,</span> <span class="nx">batchRows</span><span class="p">);</span>
      <span class="k">if</span> <span class="p">(</span><span class="nx">page</span><span class="p">.</span><span class="nx">length</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">await</span> <span class="nx">ptx</span><span class="p">.</span><span class="nx">commit</span><span class="p">();</span>
        <span class="k">break</span><span class="p">;</span>
      <span class="p">}</span>
      <span class="kd">const</span> <span class="nx">results</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">notify</span><span class="p">(</span><span class="nx">page</span><span class="p">);</span>
      <span class="k">await</span> <span class="nx">update</span><span class="p">(</span><span class="nx">results</span><span class="p">.</span><span class="nx">success</span><span class="p">);</span>
      <span class="k">await</span> <span class="nx">ptx</span><span class="p">.</span><span class="nx">commit</span><span class="p">();</span>
      <span class="nx">offset</span> <span class="o">+=</span> <span class="nx">batchRows</span><span class="p">;</span>
    <span class="p">}</span> <span class="k">while</span> <span class="p">(</span><span class="nx">offset</span> <span class="o">&lt;</span> <span class="nx">total</span><span class="p">);</span>
  <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="nx">error</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">await</span> <span class="nx">ptx</span><span class="p">.</span><span class="nx">rollback</span><span class="p">(</span><span class="nx">error</span><span class="p">);</span>
  <span class="p">}</span>
</code></pre></div></div>

<p>Everything looks quite good, we are following SAP CDS explicit transaction management well, then we decided to reproduce it in our local, we added a sleep sentence after the do-while clause and at the meantime we sent a user request to update overlapping record, then we found that the user request got stuck, that means the defect is reproducible! (There is a small episode actually, when I set the column which needs to be updated to NULL and it’s not locked, I assume it’s something related to HANA column table implementation)</p>

<p>We add <code class="language-plaintext highlighter-rouge">DEBUG=ALL</code> and restarted our server locally to print transaction BEGIN/COMMIT logs, this time we found that there is only one BEGIN and COMMIT printed which means the <code class="language-plaintext highlighter-rouge">cds.tx()</code> in loop is not working, and we only have one single transaction per job, this explained our production issue. But wait, then what’s wrong with our code?</p>

<p>We rechecked CDS documentation and our code implementation and noticed a minor difference, in our code when invoking update we are using <code class="language-plaintext highlighter-rouge">cds.run(..)</code> while in CDS doc it’s using <code class="language-plaintext highlighter-rouge">tx.run(..)</code>, we quickly realized that could be the cause of this defect, so we updated our code accordingly and restart the server to test, this time we found that everything is working as expected and each iteration successfully managed its own transaction.</p>

<p>Now the last question is what’s the difference between <code class="language-plaintext highlighter-rouge">cds.run(..)</code> and <code class="language-plaintext highlighter-rouge">tx.run(..)</code>, unfortunately we didn’t find any information is CAP documentation, so this time we dive into the implementation of cds nodejs package, cds is actually a facade and is defined in <code class="language-plaintext highlighter-rouge">@sap/cds/lib/index.js</code>, we could see that <code class="language-plaintext highlighter-rouge">cds.run</code> is a shortcut for <code class="language-plaintext highlighter-rouge">cds.db.run</code>:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// cds as shortcut to cds.db -&gt; for compatibility only</span>
<span class="nx">extend</span> <span class="p">(</span><span class="nx">cds</span><span class="p">.</span><span class="nx">__proto__</span><span class="p">)</span> <span class="p">.</span><span class="kd">with</span> <span class="p">({</span>
  <span class="kd">get</span> <span class="nx">entities</span><span class="p">(){</span> <span class="k">return</span> <span class="p">(</span><span class="nx">cds</span><span class="p">.</span><span class="nx">db</span><span class="o">||</span><span class="nx">_missing</span><span class="p">).</span><span class="nx">entities</span> <span class="p">},</span>
  <span class="na">transaction</span><span class="p">:</span> <span class="p">(...</span><span class="nx">_</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">(</span><span class="nx">cds</span><span class="p">.</span><span class="nx">db</span><span class="o">||</span><span class="nx">_missing</span><span class="p">).</span><span class="nx">transaction</span><span class="p">(...</span><span class="nx">_</span><span class="p">),</span>
  <span class="c1">// here is the cds.run defined</span>
  <span class="na">run</span><span class="p">:</span>         <span class="p">(...</span><span class="nx">_</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">(</span><span class="nx">cds</span><span class="p">.</span><span class="nx">db</span><span class="o">||</span><span class="nx">_missing</span><span class="p">).</span><span class="nx">run</span><span class="p">(...</span><span class="nx">_</span><span class="p">),</span>
  <span class="na">foreach</span><span class="p">:</span>     <span class="p">(...</span><span class="nx">_</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">(</span><span class="nx">cds</span><span class="p">.</span><span class="nx">db</span><span class="o">||</span><span class="nx">_missing</span><span class="p">).</span><span class="nx">foreach</span><span class="p">(...</span><span class="nx">_</span><span class="p">),</span>
  <span class="na">stream</span><span class="p">:</span>      <span class="p">(...</span><span class="nx">_</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">(</span><span class="nx">cds</span><span class="p">.</span><span class="nx">db</span><span class="o">||</span><span class="nx">_missing</span><span class="p">).</span><span class="nx">stream</span><span class="p">(...</span><span class="nx">_</span><span class="p">),</span>
  <span class="na">read</span><span class="p">:</span>        <span class="p">(...</span><span class="nx">_</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">(</span><span class="nx">cds</span><span class="p">.</span><span class="nx">db</span><span class="o">||</span><span class="nx">_missing</span><span class="p">).</span><span class="nx">read</span><span class="p">(...</span><span class="nx">_</span><span class="p">),</span>
  <span class="na">create</span><span class="p">:</span>      <span class="p">(...</span><span class="nx">_</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">(</span><span class="nx">cds</span><span class="p">.</span><span class="nx">db</span><span class="o">||</span><span class="nx">_missing</span><span class="p">).</span><span class="nx">create</span><span class="p">(...</span><span class="nx">_</span><span class="p">),</span>
  <span class="na">insert</span><span class="p">:</span>      <span class="p">(...</span><span class="nx">_</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">(</span><span class="nx">cds</span><span class="p">.</span><span class="nx">db</span><span class="o">||</span><span class="nx">_missing</span><span class="p">).</span><span class="nx">insert</span><span class="p">(...</span><span class="nx">_</span><span class="p">),</span>
  <span class="na">update</span><span class="p">:</span>      <span class="p">(...</span><span class="nx">_</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">(</span><span class="nx">cds</span><span class="p">.</span><span class="nx">db</span><span class="o">||</span><span class="nx">_missing</span><span class="p">).</span><span class="nx">update</span><span class="p">(...</span><span class="nx">_</span><span class="p">),</span>
  <span class="na">delete</span><span class="p">:</span>      <span class="p">(...</span><span class="nx">_</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">(</span><span class="nx">cds</span><span class="p">.</span><span class="nx">db</span><span class="o">||</span><span class="nx">_missing</span><span class="p">).</span><span class="k">delete</span><span class="p">(...</span><span class="nx">_</span><span class="p">),</span>
  <span class="na">disconnect</span><span class="p">:</span>  <span class="p">(...</span><span class="nx">_</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">(</span><span class="nx">cds</span><span class="p">.</span><span class="nx">db</span><span class="o">||</span><span class="nx">_missing</span><span class="p">).</span><span class="nx">disconnect</span><span class="p">(...</span><span class="nx">_</span><span class="p">),</span>
<span class="p">})</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">cds.db</code> is a type of <code class="language-plaintext highlighter-rouge">DatabaseService</code>, which is a child of <code class="language-plaintext highlighter-rouge">cds.Service</code>, when invoking <code class="language-plaintext highlighter-rouge">cds.run</code> it actually delegates the query parameter to <code class="language-plaintext highlighter-rouge">cds.Service.run</code>:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/**
 * Querying API to send synchronous requests...
 */</span>
<span class="nx">run</span> <span class="p">(</span><span class="nx">query</span><span class="p">,</span> <span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="k">typeof</span> <span class="nx">query</span> <span class="o">===</span> <span class="dl">'</span><span class="s1">function</span><span class="dl">'</span><span class="p">)</span> <span class="p">{</span>
    <span class="kd">const</span> <span class="nx">ctx</span> <span class="o">=</span> <span class="nx">cds</span><span class="p">.</span><span class="nx">context</span><span class="p">,</span> <span class="nx">fn</span> <span class="o">=</span> <span class="nx">query</span>
    <span class="k">if</span> <span class="p">(</span><span class="nx">ctx</span><span class="p">?.</span><span class="nx">tx</span> <span class="o">&amp;&amp;</span> <span class="o">!</span><span class="nx">ctx</span><span class="p">.</span><span class="nx">tx</span><span class="p">.</span><span class="nx">_done</span><span class="p">)</span> <span class="p">{</span>
      <span class="k">return</span> <span class="nx">fn</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">tx</span><span class="p">(</span><span class="nx">ctx</span><span class="p">))</span> <span class="c1">// with nested tx</span>
    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
      <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">tx</span> <span class="p">(</span><span class="nx">fn</span><span class="p">)</span> <span class="c1">// with root tx</span>
    <span class="p">}</span>
  <span class="p">}</span>
  <span class="kd">const</span> <span class="nx">req</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Request</span> <span class="p">({</span> <span class="nx">query</span><span class="p">,</span> <span class="nx">data</span> <span class="p">})</span>
  <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">dispatch</span> <span class="p">(</span><span class="nx">req</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">cds.Service.dispatch</code> is using <code class="language-plaintext highlighter-rouge">srv-dispatch.js</code>, inside the code implementation we could see that by default it will use the context of current cds and execute the query within the context.tx:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">exports</span><span class="p">.</span><span class="nx">dispatch</span> <span class="o">=</span> <span class="k">async</span> <span class="kd">function</span> <span class="nx">dispatch</span> <span class="p">(</span><span class="nx">req</span><span class="p">)</span> <span class="p">{</span> <span class="c1">//NOSONAR</span>

  <span class="c1">// Ensure we are in a proper transaction</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="k">this</span><span class="p">.</span><span class="nx">context</span><span class="p">)</span> <span class="p">{</span>
    <span class="kd">const</span> <span class="nx">ctx</span> <span class="o">=</span> <span class="nx">cds</span><span class="p">.</span><span class="nx">context</span>
    <span class="k">if</span> <span class="p">(</span><span class="nx">ctx</span><span class="p">?.</span><span class="nx">tx</span> <span class="o">&amp;&amp;</span> <span class="o">!</span><span class="nx">ctx</span><span class="p">.</span><span class="nx">tx</span><span class="p">.</span><span class="nx">_done</span><span class="p">)</span> <span class="p">{</span>
      <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">tx</span> <span class="p">(</span><span class="nx">ctx</span><span class="p">)</span> <span class="p">.</span><span class="nx">dispatch</span><span class="p">(</span><span class="nx">req</span><span class="p">)</span>      <span class="c1">// with nested tx</span>
    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
      <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">tx</span> <span class="p">(</span><span class="nx">tx</span> <span class="o">=&gt;</span> <span class="nx">tx</span><span class="p">.</span><span class="nx">dispatch</span><span class="p">(</span><span class="nx">req</span><span class="p">))</span>  <span class="c1">// with root tx</span>
    <span class="p">}</span>
  <span class="p">}</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">req</span><span class="p">.</span><span class="nx">tx</span><span class="p">)</span> <span class="nx">req</span><span class="p">.</span><span class="nx">tx</span> <span class="o">=</span> <span class="k">this</span> <span class="c1">// `this` is a tx from now on...</span>
  <span class="c1">// ...omitted</span>
  <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">handle</span><span class="p">(</span><span class="nx">req</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div></div>

<p>From above we could find that the actual difference between <code class="language-plaintext highlighter-rouge">cds.run(..)</code> and <code class="language-plaintext highlighter-rouge">tx.run(..)</code>, briefly speaking that they are using different transaction(what a short answer).</p>

<h3 id="references">References</h3>

<p>[1] https://help.sap.com/docs/SAP_HANA_PLATFORM/bed8c14f9f024763b0777aa72b5436f6/dd111c40e43c4161a59769c7e959a86b.html</p>

<p>[2] https://cap.cloud.sap/docs/node.js/cds-tx</p>]]></content><author><name>Leo</name><email>mail@nleo.me</email></author><category term="en" /><summary type="html"><![CDATA[Write DB record(s) concurrently or parallelly is a common situation, while it can easily result in defects which is hard to detect in PR review and often cause disasters in production. My previous blog mentioned a deadlock issue which is caused by such scenario, briefly speaking the root cause is that we are trying to update/delete same batch records parallelly in different order and locked in mutual finally.]]></summary></entry><entry><title type="html">Analysis for Failed to fetch CSRF token in @sap-cloud-sdk/http-client</title><link href="https://nleo.me/en/2023/06/13/405_prod_issue_analysis.html" rel="alternate" type="text/html" title="Analysis for Failed to fetch CSRF token in @sap-cloud-sdk/http-client" /><published>2023-06-13T04:10:21+00:00</published><updated>2023-06-13T04:10:21+00:00</updated><id>https://nleo.me/en/2023/06/13/405_prod_issue_analysis</id><content type="html" xml:base="https://nleo.me/en/2023/06/13/405_prod_issue_analysis.html"><![CDATA[<h2 id="tldr">TL;DR</h2>

<ol>
  <li>HEAD is not automatically supported for cds odata action/function.</li>
  <li>APIM policy may configured to only accept <code class="language-plaintext highlighter-rouge">GET</code> and <code class="language-plaintext highlighter-rouge">POST</code></li>
</ol>

<h2 id="issue-description">Issue Description</h2>

<p>We received several warning logs in prod environment which showed that lots of csrf token request failed.</p>

<h2 id="how-to-reproduce">How to reproduce</h2>

<ol>
  <li>
    <p>Go to dev APIM and Click ‘Test’ in the left tab, then start debug as below:</p>

    <p><img src="/assets/images/posts/2023-06-13/image-20230612135640689.png" alt="image-20230612135640689" /></p>
  </li>
  <li>
    <p>Clear user cache (take my i-number as an example): <code class="language-plaintext highlighter-rouge">hdel user zzz</code></p>
  </li>
  <li>
    <p>Verify user cache is empty: <code class="language-plaintext highlighter-rouge">hget user zzz</code>, Should return ‘No result’</p>
  </li>
  <li>
    <p>Enter: <a href="https://origin.learning-dev.sap.com/service/runtime/les/getUserEntitlement()">https://origin.learning-dev.sap.com/service/runtime/les/getUserEntitlement()</a></p>

    <p><img src="/assets/images/posts/2023-06-13/image-20230612135821245.png" alt="image-20230612135821245" /></p>
  </li>
  <li>
    <p>Go back and click Refresh, two error request with HEAD, one is ‘/userLogin/’ and another is ‘/userLogin’:</p>

    <p><img src="/assets/images/posts/2023-06-13/image-20230612135932088.png" alt="image-20230612135932088" /></p>
  </li>
</ol>

<h2 id="further-analysis">Further analysis</h2>

<ol>
  <li>
    <p>In dev environment, open kibana and search with <code class="language-plaintext highlighter-rouge">"userLogin" AND component_name:"progress" AND "HEAD" AND organization_name:"sap-learning-dev-venusaur"</code></p>

    <p><img src="/assets/images/posts/2023-06-13/image-20230612152957380.png" alt="image-20230612152957380" /></p>
  </li>
  <li>
    <p>Copy correlation_id for these two requests: <code class="language-plaintext highlighter-rouge">/userLogin</code> and <code class="language-plaintext highlighter-rouge">/userLogin/</code></p>

    <p><img src="/assets/images/posts/2023-06-13/image-20230612153124617.png" alt="image-20230612153124617" /></p>

    <p><img src="/assets/images/posts/2023-06-13/image-20230612153145501.png" alt="image-20230612153145501" /></p>
  </li>
  <li>
    <p>We can see two HEAD requests sent to progress application and both failed.</p>
  </li>
  <li>
    <p>Then we checked the source code and found that every time the error thrown, there will be a debug level log indicating that fetch csrf token failed.</p>

    <ul>
      <li>
        <p>BTW, in data-approuter, the @sap-cloud-sdk/http-client is “^2.7.1” and in runtime it’s “^3.1.1”, the csrf request implementation is slightly different:</p>

        <div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// in 2.7.1</span>
<span class="c1">// csrf-token-header.js</span>
<span class="kd">function</span> <span class="nx">makeCsrfRequest</span><span class="p">(</span><span class="nx">destination</span><span class="p">,</span> <span class="nx">requestConfig</span><span class="p">)</span> <span class="p">{</span>
    <span class="kd">const</span> <span class="nx">axiosConfig</span> <span class="o">=</span> <span class="p">{</span>
        <span class="na">method</span><span class="p">:</span> <span class="dl">'</span><span class="s1">head</span><span class="dl">'</span><span class="p">,</span>
        <span class="p">...</span><span class="nx">requestConfig</span><span class="p">,</span>
        <span class="na">params</span><span class="p">:</span> <span class="p">{</span>
            <span class="na">custom</span><span class="p">:</span> <span class="nx">requestConfig</span><span class="p">.</span><span class="nx">params</span> <span class="o">||</span> <span class="p">{},</span>
            <span class="na">requestConfig</span><span class="p">:</span> <span class="p">{}</span>
        <span class="p">},</span>
        <span class="na">headers</span><span class="p">:</span> <span class="p">{</span>
            <span class="na">custom</span><span class="p">:</span> <span class="nx">buildCsrfFetchHeaders</span><span class="p">(</span><span class="nx">requestConfig</span><span class="p">.</span><span class="nx">headers</span><span class="p">),</span>
            <span class="na">requestConfig</span><span class="p">:</span> <span class="p">{}</span>
        <span class="p">}</span>
    <span class="p">};</span>
    <span class="c1">// The S/4 does a redirect if the CSRF token is fetched in case the '/' is not in the URL.</span>
    <span class="c1">// TODO: remove once https://github.com/axios/axios/issues/3369 is really fixed. Issue is closed but problem stays.</span>
    <span class="kd">const</span> <span class="nx">requestConfigWithTrailingSlash</span> <span class="o">=</span> <span class="nx">appendSlash</span><span class="p">(</span><span class="nx">axiosConfig</span><span class="p">);</span>
    <span class="k">return</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nx">http_client_1</span><span class="p">.</span><span class="nx">executeHttpRequest</span><span class="p">)(</span><span class="nx">destination</span><span class="p">,</span> <span class="nx">requestConfigWithTrailingSlash</span><span class="p">)</span>
        <span class="p">.</span><span class="nx">then</span><span class="p">(</span><span class="nx">response</span> <span class="o">=&gt;</span> <span class="nx">response</span><span class="p">.</span><span class="nx">headers</span><span class="p">)</span>
        <span class="p">.</span><span class="k">catch</span><span class="p">(</span><span class="nx">error1</span> <span class="o">=&gt;</span> <span class="p">{</span>
        <span class="kd">const</span> <span class="nx">headers1</span> <span class="o">=</span> <span class="nx">getResponseHeadersFromError</span><span class="p">(</span><span class="nx">error1</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="nx">hasCsrfToken</span><span class="p">(</span><span class="nx">headers1</span><span class="p">))</span> <span class="p">{</span>
            <span class="k">return</span> <span class="nx">headers1</span><span class="p">;</span>
        <span class="p">}</span>
        <span class="nx">logger</span><span class="p">.</span><span class="nx">warn</span><span class="p">(</span><span class="k">new</span> <span class="nx">util_1</span><span class="p">.</span><span class="nx">ErrorWithCause</span><span class="p">(</span><span class="s2">`First attempt to fetch CSRF token failed with the URL: </span><span class="p">${</span><span class="nx">requestConfigWithTrailingSlash</span><span class="p">.</span><span class="nx">url</span><span class="p">}</span><span class="s2">. Retrying without trailing slash.`</span><span class="p">,</span> <span class="nx">error1</span><span class="p">));</span>
        <span class="kd">const</span> <span class="nx">requestConfigWithOutTrailingSlash</span> <span class="o">=</span> <span class="nx">removeSlash</span><span class="p">(</span><span class="nx">axiosConfig</span><span class="p">);</span>
        <span class="k">return</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nx">http_client_1</span><span class="p">.</span><span class="nx">executeHttpRequest</span><span class="p">)(</span><span class="nx">destination</span><span class="p">,</span> <span class="nx">requestConfigWithOutTrailingSlash</span><span class="p">)</span>
            <span class="p">.</span><span class="nx">then</span><span class="p">(</span><span class="nx">response</span> <span class="o">=&gt;</span> <span class="nx">response</span><span class="p">.</span><span class="nx">headers</span><span class="p">)</span>
            <span class="p">.</span><span class="k">catch</span><span class="p">(</span><span class="nx">error2</span> <span class="o">=&gt;</span> <span class="p">{</span>
            <span class="kd">const</span> <span class="nx">headers2</span> <span class="o">=</span> <span class="nx">getResponseHeadersFromError</span><span class="p">(</span><span class="nx">error2</span><span class="p">);</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">hasCsrfToken</span><span class="p">(</span><span class="nx">headers2</span><span class="p">))</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nx">headers2</span><span class="p">;</span>
            <span class="p">}</span>
            <span class="nx">logger</span><span class="p">.</span><span class="nx">warn</span><span class="p">(</span><span class="k">new</span> <span class="nx">util_1</span><span class="p">.</span><span class="nx">ErrorWithCause</span><span class="p">(</span><span class="s2">`Second attempt to fetch CSRF token failed with the URL: </span><span class="p">${</span><span class="nx">requestConfigWithOutTrailingSlash</span><span class="p">.</span><span class="nx">url</span><span class="p">}</span><span class="s2">. No CSRF token fetched.`</span><span class="p">,</span> <span class="nx">error2</span><span class="p">));</span>
            <span class="c1">// todo suggest to disable csrf token handling when the API is implemented</span>
            <span class="k">return</span> <span class="p">{};</span>
        <span class="p">});</span>
    <span class="p">});</span>
<span class="p">}</span>
</code></pre></div>        </div>

        <div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// in 3.1.1</span>
<span class="c1">// csrf-token-middleware.js</span>
<span class="k">async</span> <span class="kd">function</span> <span class="nx">makeCsrfRequest</span><span class="p">(</span><span class="nx">requestConfig</span><span class="p">,</span> <span class="nx">options</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">try</span> <span class="p">{</span>
        <span class="kd">const</span> <span class="nx">response</span> <span class="o">=</span> <span class="k">await</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nx">internal_1</span><span class="p">.</span><span class="nx">executeWithMiddleware</span><span class="p">)(</span><span class="nx">options</span><span class="p">.</span><span class="nx">middleware</span><span class="p">,</span> <span class="p">{</span>
            <span class="na">fn</span><span class="p">:</span> <span class="nx">axios_1</span><span class="p">.</span><span class="k">default</span><span class="p">.</span><span class="nx">request</span><span class="p">,</span>
            <span class="na">fnArgument</span><span class="p">:</span> <span class="nx">requestConfig</span><span class="p">,</span>
            <span class="na">context</span><span class="p">:</span> <span class="nx">options</span><span class="p">.</span><span class="nx">context</span>
        <span class="p">});</span>
        <span class="k">return</span> <span class="nx">findCsrfHeader</span><span class="p">(</span><span class="nx">response</span><span class="p">.</span><span class="nx">headers</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">catch</span> <span class="p">(</span><span class="nx">error</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="nx">findCsrfHeader</span><span class="p">(</span><span class="nx">error</span><span class="p">.</span><span class="nx">response</span><span class="p">?.</span><span class="nx">headers</span><span class="p">))</span> <span class="p">{</span>
            <span class="k">return</span> <span class="nx">findCsrfHeader</span><span class="p">(</span><span class="nx">error</span><span class="p">.</span><span class="nx">response</span><span class="p">?.</span><span class="nx">headers</span><span class="p">);</span>
        <span class="p">}</span>
        <span class="nx">logger</span><span class="p">.</span><span class="nx">warn</span><span class="p">(</span><span class="k">new</span> <span class="nx">util_1</span><span class="p">.</span><span class="nx">ErrorWithCause</span><span class="p">(</span><span class="s2">`Failed to get CSRF token from  URL: </span><span class="p">${</span><span class="nx">requestConfig</span><span class="p">.</span><span class="nx">url</span><span class="p">}</span><span class="s2">.`</span><span class="p">,</span> <span class="nx">error</span><span class="p">));</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div>        </div>
      </li>
    </ul>
  </li>
  <li>
    <p>Check source code and found that the API is odata function, which means it does not support HEAD method, then it explained why we received 405 error.</p>
  </li>
  <li>
    <p>Is that enough?</p>
  </li>
</ol>

<h2 id="following-questions">Following Questions</h2>

<ol>
  <li>
    <p>Why the code is deployed one month ago and only observed recently?</p>

    <blockquote>
      <p>In runtime application, the ‘/userLogin’ API is only invoked by ‘/les/getUserEntitlement()’, and it’s being tested since 2023-06-06, check logs below:</p>

      <p><img src="/assets/images/posts/2023-06-13/image-20230612133448857.png" alt="image-20230612133448857" /></p>
    </blockquote>
  </li>
  <li>
    <p>‘/userLogin’ API is also invoked in data-approuter application, and it’s being invoked the same way, why it’s not observed before?</p>

    <blockquote>
      <p>Log config is set to <code class="language-plaintext highlighter-rouge">error</code> in data-approuter.</p>

      <p><img src="/assets/images/posts/2023-06-13/image-20230612155349552.png" alt="image-20230612155349552" /></p>

      <p>Actually it also failed when send HEAD request from data-approuter to APIM, we can check that from APIM debug console as previously stated.</p>

      <ol>
        <li>Start debug (RECOMMEND to do in private dev)</li>
        <li>Go to: <a href="https://sap-learning-private-dev1-com-sap-learning-data-approuter.cfapps.eu10-004.hana.ondemand.com/?userlogin=true">https://sap-learning-private-dev1-com-sap-learning-data-approuter.cfapps.eu10-004.hana.ondemand.com/?userlogin=true</a></li>
        <li>Click refresh and you will see two HEAD request errors</li>
      </ol>
    </blockquote>
  </li>
  <li>
    <p>Why observed different logs in prod/stage vs test/dev</p>

    <blockquote>
      <p>The APIM policies configuration is different, in stage/prod there is a policy to check if the method is allowed:</p>

      <p><img src="/assets/images/posts/2023-06-13/image-20230612160731691.png" alt="image-20230612160731691" />
<img src="/assets/images/posts/2023-06-13/image-20230612160746024.png" alt="image-20230612160746024" /></p>

      <p>It’s not configured in dev/test:
<img src="/assets/images/posts/2023-06-13/image-20230612160817915.png" alt="image-20230612160817915" /></p>
    </blockquote>
  </li>
</ol>

<h2 id="good-to-know">Good to Know</h2>

<ul>
  <li>DO NOT perform csrf token fetch for internal invocation</li>
  <li>DO NOT manually copy-paste for cross environment configurations</li>
  <li>DO NOT force global log level in the code</li>
  <li>DO NOT force log level to ERROR, it’s not friendly for troubleshooting</li>
</ul>]]></content><author><name>Leo</name><email>mail@nleo.me</email></author><category term="en" /><summary type="html"><![CDATA[TL;DR]]></summary></entry><entry><title type="html">初探HTTP/3</title><link href="https://nleo.me/cn/2023/05/25/http3_first_insight.html" rel="alternate" type="text/html" title="初探HTTP/3" /><published>2023-05-25T07:20:11+00:00</published><updated>2023-05-25T07:20:11+00:00</updated><id>https://nleo.me/cn/2023/05/25/http3_first_insight</id><content type="html" xml:base="https://nleo.me/cn/2023/05/25/http3_first_insight.html"><![CDATA[<h2 id="从http11到http2">从HTTP/1.1到HTTP/2</h2>

<p>HTTP是Web的基础协议，从上个世纪90年代问世以来经历了数个版本的演化，其中使用时间最长也最广为人知的便是HTTP/1.1协议，它通过支持TCP连接重用、提供更为合理的缓存控制等创造性的解决了HTTP/1.0中存在的诸多问题，并在1997年以RFC 2068<sup id="fnref:fn1" role="doc-noteref"><a href="#fn:fn1" class="footnote" rel="footnote">1</a></sup>发布，在接下来的十多年间一直是最为主流的HTTP协议版本，但随着现代Web应用复杂性的提升，HTTP/1.1的性能越来越难以满足要求，其中最受诟病的莫过于HOLB（Head-of-Line Blocking，队头阻塞）。由于HTTP/1.1不支持多路复用，且Pipeline技术由于实现困难，一般浏览器默认采用串行发送请求，意味着后续请求需要等待前面的请求完成，虽然HTTP/1.1通过支持建立更多的TCP连接来缓解这一问题，但由于TCP连接数有限制，因此实际表现并不理想。</p>

<p>为此Google开发了SPDY协议，其采用多路复用技术并支持对Header进行压缩，很好的解决了HTTP/1.1的性能问题，从而成为HTTP/2协议的基础，2015年RFC 7540<sup id="fnref:fn2" role="doc-noteref"><a href="#fn:fn2" class="footnote" rel="footnote">2</a></sup>的发表标志着HTTP/2正式问世。HTTP/2通过Stream实现多路复用，不仅从应用层解决了HOLB问题，同时也避免了创建额外的TCP连接的开销，大大提高了网页加载速度，除此之外，HTTP/2表现出良好的兼容性及易升级性也帮助它迅速占领了主流站点，取得了极大的成功。</p>

<h2 id="从-http2-到-http3">从 HTTP/2 到 HTTP/3</h2>
<p>然而，HTTP/2也有一些致命缺陷，它底层所依赖的TCP协议存在众所周知的慢启动问题，以及TCP协议的重传机制也会导致发送窗口队头阻塞（从HTTP层转移到了TCP层）。此外，TCP拥塞控制算法通常采用“加性增、乘性减”的方式，当遇到丢包时，会减半发送窗口从而导致流量下降。因此，在网络状况不佳的情况下，HTTP/2的表现甚至不如HTTP/1.1<sup id="fnref:fn5" role="doc-noteref"><a href="#fn:fn5" class="footnote" rel="footnote">3</a></sup>。
为了解决TCP协议的固有问题，Google又开发了实验性的QUIC（Quick UDP Internet Connections，快速UDP互联网连接）协议<sup id="fnref:fn6" role="doc-noteref"><a href="#fn:fn6" class="footnote" rel="footnote">4</a></sup>以替换TCP协议，QUIC协议相比较于TCP协议有以下主要特性：</p>

<ol>
  <li>基于UDP协议：TCP协议是面向连接的可靠传输协议，它通过序号、确认和重传来保障可靠性，而UDP是一种不可靠传输协议。QUIC使用前向纠错、重传和拥塞控制等技术来处理错误，利用Stream实现数据传输，每个Stream都是单独进行流控制，当出现丢包时只会影响该数据报内部相关的Stream而不会影响其他Stream的数据传输，从而避免了TCP协议的队头阻塞问题。</li>
  <li>极低的建立连接开销：传统的HTTPS协议栈由TCP+TLS组成，建立一次HTTPS连接需要进行多次握手，而QUIC协议内置对数据加密的支持，从而减少了初次建立连接的握手次数。</li>
</ol>

<p><img src="/assets/images/posts/2023-05-25/1.png" alt="" title="建立HTTPS连接的握手过程，来源于：
https://upload.wikimedia.org/wikipedia/commons/4/41/Tcp-vs-quic-handshake.svg" /></p>

<ol>
  <li>用户态协议：与工作在内核态的TCP协议不同，QUIC协议工作在用户态，从而将传输协议与操作系统解耦，避免了协议僵化问题，可以更快的进行技术迭代以更好的满足快速变化的用户需求。</li>
</ol>

<p>QUIC协议经过多年的实践表现出良好的性能，随后被提议作为HTTP/2的传输层协议，即“HTTP over QUIC”，2018年被更名为HTTP/3并在2022年以RFC 9114<sup id="fnref:fn3" role="doc-noteref"><a href="#fn:fn3" class="footnote" rel="footnote">5</a></sup>发布成为新的标准。截止到2023年5月，有25.9%<sup id="fnref:fn4" role="doc-noteref"><a href="#fn:fn4" class="footnote" rel="footnote">6</a></sup>的网站正在使用HTTP/3。</p>

<h2 id="http3-性能初探">HTTP/3 性能初探</h2>
<p>QUIC协议诞生已有十年之久，研究人员针对QUIC或HTTP/3的性能做了不少研究。最早的研究可能来自于R.Das[^fn14]在2014年对gQUIC（Google QUIC）的性能评估，他通过比较HTTP/1.1、SPDY和QUIC的PLT（Page Load Time，页面加载时间）发现QUIC协议在低带宽高延迟的场景下性能可以提升10-60%。</p>

<p>Konrad Wolsing<sup id="fnref:fn7" role="doc-noteref"><a href="#fn:fn7" class="footnote" rel="footnote">7</a></sup>及其研究团队认为在对比QUIC和TCP性能时忽略TCP协议本身存在的优化空间是不严谨的，而且过去的研究显示PLT（Page Load Time，页面加载时间）和用户可感知的速度没有太大关联，为此他们对TCP参数进行了针对性调优，并使用BBR拥塞控制算法以替换默认的CUIBIC算法，同时引入FVC（First Visual Change）、VC85（Visual Complete 85%）和SI（Speed Index）等指标比对QUIC和TCP性能差异，通过Mahimahi框架进行流量重放，结果显示经过调优后的TCP性能大幅提升，但总体而言QUIC因0-RTT（0 Round Trip Time，0往返时间）设计仍然占优。</p>

<p>Alexander Yu<sup id="fnref:fn8" role="doc-noteref"><a href="#fn:fn8" class="footnote" rel="footnote">8</a></sup>及其研究团队指出过去的QUIC协议性能研究都是在非生产环境进行，数据不具有说服力，因此他们使用Google、Facebook、Cloudflare公开的端点，分别对单对象资源和多对象网页进行测试，结果显示单对象资源在低丢包率或低延迟场景下当负荷较低（100KB）时HTTP/3表现均优于HTTP/2，而负荷大于1MB的情况下两者表现接近，但有趣的是在负荷大于5MB的情况下Cloudflare的HTTP/3端点表现远逊于HTTP/2，进一步研究显示该性能差距主要是由于Cloudflare的QUIC协议采用CUBIC拥塞控制算法而TCP协议采用BBR拥塞控制算法，多对象网页的性能测试结果显示QUIC协议针对HOLB的设计并没有带来明显的网页加载性能提升，考虑到QUIC协议本身的实现难度及不同的实现对性能的提升效果也有较大差别，因此他们认为可能在很多场景下HTTP/3并不能让人感到惊艳。</p>

<p>Martino Trevisan<sup id="fnref:fn9" role="doc-noteref"><a href="#fn:fn9" class="footnote" rel="footnote">9</a></sup>团队也对Google、Facebook、Cloudflare等早期支持HTTP/3的站点进行了性能测试，从网络延迟、丢包率、带宽等多个维度对比了HTTP/1.1、HTTP/2和HTTP/3的PLT和Speed Index指标，研究显示高延迟、高丢包率和低带宽场景下HTTP/3表现优于其他两者，例如对于增加200ms延迟的情况下，HTTP/3的PLT中位数是5.4s，而HTTP/2和HTTP/1.1分别是5.8s和6.4s。同时研究人员也注意到不同的服务提供商的HTTP/3表现也有差别，这可能跟底层协议的具体实现有关，例如在1Mb/s带宽场景下Facebook &lt; Cloudflare &lt; Google，而在增加200ms延迟场景下Cloudflare &lt; Google &lt; Facebook。</p>

<p>Saif D<sup id="fnref:fn11" role="doc-noteref"><a href="#fn:fn11" class="footnote" rel="footnote">10</a></sup>团队认为过去的研究往往仅关注底层QUIC协议（一般为gQUIC）与TCP协议的性能对比，并且指标一般都以PLT为主不够丰富，因此他们使用开源的LightHouse对HTTP/2+TLS1.3和HTTP/3（Cloudflare的QUICHE@98757ca）的QoE（Quality of Experience，用户体验质量）进行比较，具体性能指标权重分布见表1。研究结果显示，虽然总体吞吐量上HTTP/3比HTTP/2表现更好，但不管是在网络可靠的场景下还是在引入网络延迟和丢包之后，HTTP/3的 QoE总分均不如HTTP/2+TLS1.3，特别是LCP指标大幅落后，这也佐证了Cloudflare官方博客的性能数据：HTTP/3比HTTP/2要慢1-4%。</p>

<table>
  <thead>
    <tr>
      <th>Item</th>
      <th>Percentage</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>First Contentful Paint (FCP)</td>
      <td>15%</td>
      <td>The time delta between first navigating to theweb page and the browser rendering the very first DOM content.</td>
    </tr>
    <tr>
      <td>Time to Interactive (TTI)</td>
      <td>15%</td>
      <td>1. The FCP has completed <br /> 2. Handlers are loaded for page elements <br /> 3. The page responds to input within 50ms.</td>
    </tr>
    <tr>
      <td>Speed Index(SI)</td>
      <td>15%</td>
      <td>The time it takes for objects to be visibly displayed during page load.</td>
    </tr>
    <tr>
      <td>Largest Contentful Paint (LCP)</td>
      <td>25%</td>
      <td>The time it takes for the element on the page with the largest payload to have been completely rendered.</td>
    </tr>
    <tr>
      <td>Total Blocking Time (TBT)</td>
      <td>25%</td>
      <td>In the time between FCP and TTI, tasks taking longer than 50ms are summed into TBT. <br /> Timing starts after 50ms of task execution.</td>
    </tr>
    <tr>
      <td>Cumulative Layout Shift (CLS)</td>
      <td>5%</td>
      <td>Quantifies the page’s stability as resources are loaded or DOMs are added. A higher score means more frequent layout shifts.</td>
    </tr>
  </tbody>
</table>

<p>A. Gupta<sup id="fnref:fn12" role="doc-noteref"><a href="#fn:fn12" class="footnote" rel="footnote">11</a></sup>及其研究团队同样使用了LightHouse分别对本地服务器、同区域（印度）服务器、全球（北美）服务器进行了性能测试，在吞吐量指标上HTTP/2全面占优，仅当使用无线连接且服务器在北美时QUICHE-H3表现亮眼，研究人员认为这证实了H3在网络不稳定的场景下有更好的性能。除了吞吐量之外，研究人员也对FCP、SI、LCP、TTI进行了对比，同样仅当使用无线连接且服务器在北美时H3性能略优于H2，其他均逊色于H2。不过，虽然整体性能测试结果显示H3不尽如人意，但研究人员认为H3仍在实验阶段，还可以不断优化，有很大的进步空间。</p>

<h2 id="总结">总结</h2>
<p>本文简单介绍了HTTP发展历程和HTTP/3的几个主要特性，并研究了一些针对HTTP/3与HTTP/2性能评估的论文。尽管HTTP/3声称可以解决HOLB，且具有更低的连接建立开销，但许多研究表明，HTTP/3的性能优势并不一定明显，还依赖具体的实现和网络条件。一般来说，在高延迟、高丢包率和低带宽等不稳定的网络环境下，HTTP/3表现更好，但是不同厂商的QUIC协议具体实现不同，例如Cloudflare采用CUBIC拥塞控制算法而Google采用的是BBR拥塞控制算法，这也是导致性能差异明显的一大原因。</p>

<p>不过，本文未对不同使用场景如视频播放、物联网等进行研究，也没有涉及到移动网络。虽然HOLB在加载网页场景下并没有亮眼的表现，但对于视频播放也许有不错的提升。而不同代际的移动网络如3G，4G，5G其网络带宽和延迟差距较大，HTTP/3或许会有出色的表现，此外，HTTP/3的0 RTT机制在高速移动中的设备切换基站连接时应具有良好的用户体验。当然，由于个人水平有限，以上观点可能存在不准确之处，敬请谅解。</p>

<h2 id="参考文献">参考文献</h2>

<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:fn1" role="doc-endnote">
      <p>RFC 2068. <a href="https://datatracker.ietf.org/doc/html/rfc2068">https://datatracker.ietf.org/doc/html/rfc2068</a> <a href="#fnref:fn1" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:fn2" role="doc-endnote">
      <p>RFC 7540. <a href="https://datatracker.ietf.org/doc/html/rfc7540">https://datatracker.ietf.org/doc/html/rfc7540</a> <a href="#fnref:fn2" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:fn5" role="doc-endnote">
      <p>Saxce H D ,  Oprescu I ,  Chen Y . Is HTTP/2 really faster than HTTP/1.1?[C]// IEEE INFOCOM 2015 - IEEE Conference on Computer Communications Workshops (INFOCOM WKSHPS). IEEE, 2015. <a href="#fnref:fn5" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:fn6" role="doc-endnote">
      <p>Langley A ,  Iyengar J ,  Bailey J , et al. The QUIC Transport Protocol: Design and Internet-Scale Deployment[C]// the Conference of the ACM Special Interest Group. ACM, 2017. <a href="#fnref:fn6" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:fn3" role="doc-endnote">
      <p>RFC 9114. <a href="https://datatracker.ietf.org/doc/html/rfc9114">https://datatracker.ietf.org/doc/html/rfc9114</a> <a href="#fnref:fn3" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:fn4" role="doc-endnote">
      <p>Usage statistics of HTTP/3 for websites. <a href="https://w3techs.com/technologies/details/ce-http3">https://w3techs.com/technologies/details/ce-http3</a> <a href="#fnref:fn4" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:fn7" role="doc-endnote">
      <p>Wolsing K , J Rüth,  Wehrle K , et al. A Performance Perspective on Web Optimized Protocol Stacks: TCP+TLS+HTTP/2 vs. QUIC[J].  2019. <a href="#fnref:fn7" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:fn8" role="doc-endnote">
      <p>Yu A ,  Benson T A . Dissecting Performance of Production QUIC[C]// WWW ‘21: The Web Conference 2021. 2021. <a href="#fnref:fn8" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:fn9" role="doc-endnote">
      <p>Trevisan M ,  Giordano D ,  Drago I , et al. Measuring HTTP/3: Adoption and Performance[C]// 2021. <a href="#fnref:fn9" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:fn11" role="doc-endnote">
      <p>A. Gupta and R. Bartos, “User Experience Evaluation of HTTP/3 in Real-World Deployment Scenarios,” 2022 25th Conference on Innovation in Clouds, Internet and Networks (ICIN), Paris, France, 2022, pp. 17-23, doi: 10.1109/ICIN53892.2022.9758130. <a href="#fnref:fn11" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:fn12" role="doc-endnote">
      <p>Das S R . Evaluation of QUIC on web page performance[J]. massachusetts institute of technology, 2014. <a href="#fnref:fn12" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Leo</name><email>mail@nleo.me</email></author><category term="cn" /><summary type="html"><![CDATA[从HTTP/1.1到HTTP/2]]></summary></entry><entry><title type="html">Destination cache in Approuter and Connectivity</title><link href="https://nleo.me/en/2023/05/04/approuter_destination_cache.html" rel="alternate" type="text/html" title="Destination cache in Approuter and Connectivity" /><published>2023-05-04T10:31:45+00:00</published><updated>2023-05-04T10:31:45+00:00</updated><id>https://nleo.me/en/2023/05/04/approuter_destination_cache</id><content type="html" xml:base="https://nleo.me/en/2023/05/04/approuter_destination_cache.html"><![CDATA[<h2 id="connectivity-in-sap-cloud-sdk">Connectivity in @sap-cloud-sdk</h2>

<h3 id="tldr">TL;DR</h3>

<ul>
  <li>Built-in cache mechanism with <code class="language-plaintext highlighter-rouge">useCache</code> in option</li>
  <li>By default expiration time is 5 mins and no eviction</li>
</ul>

<hr />
<p>By default, if we use <code class="language-plaintext highlighter-rouge">executeHttpRequest</code> from <code class="language-plaintext highlighter-rouge">@sap-cloud-sdk/http-client</code>, the function signature is:</p>

<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">executeHttpRequest</span><span class="o">&lt;</span><span class="nx">T</span> <span class="kd">extends</span> <span class="nx">HttpRequestConfig</span><span class="o">&gt;</span><span class="p">(</span><span class="nx">destination</span><span class="p">:</span> <span class="nx">DestinationOrFetchOptions</span><span class="p">,</span> <span class="nx">requestConfig</span><span class="p">:</span> <span class="nx">T</span><span class="p">,</span> <span class="nx">options</span><span class="p">?:</span> <span class="nx">HttpRequestOptions</span><span class="p">):</span> <span class="nb">Promise</span><span class="o">&lt;</span><span class="nx">HttpResponse</span><span class="o">&gt;</span><span class="p">;</span>
</code></pre></div></div>
<p>The first arg accepts a <code class="language-plaintext highlighter-rouge">Destination</code> or <code class="language-plaintext highlighter-rouge">DestinationFetchOptions</code>, currently in our system, we always use <code class="language-plaintext highlighter-rouge">DestinationFetchOptions</code>.</p>

<p>Before <code class="language-plaintext highlighter-rouge">http-client</code> perform request, it will first try to resolve destination by options, the detailed implementation sequential flow looks like below:</p>

<p><img src="/assets/images/posts/2023-05-04/1.jpg" alt="" /></p>

<p><code class="language-plaintext highlighter-rouge">destination-accessor.getDestination</code> actually will not call getDestinationFromDestinationService only, in the above diagram it’s just simplified for better understanding, here is the detailed code logic:</p>

<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">async</span> <span class="kd">function</span> <span class="nx">getDestination</span><span class="p">(</span><span class="nx">options</span><span class="p">)</span> <span class="p">{</span>
    <span class="kd">const</span> <span class="nx">destination</span> <span class="o">=</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nx">destination_from_env_1</span><span class="p">.</span><span class="nx">searchEnvVariablesForDestination</span><span class="p">)(</span><span class="nx">options</span><span class="p">)</span> <span class="o">||</span>
        <span class="p">(</span><span class="k">await</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nx">destination_from_registration_1</span><span class="p">.</span><span class="nx">searchRegisteredDestination</span><span class="p">)(</span><span class="nx">options</span><span class="p">))</span> <span class="o">||</span>
        <span class="p">(</span><span class="k">await</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nx">destination_from_vcap_1</span><span class="p">.</span><span class="nx">searchServiceBindingForDestination</span><span class="p">)(</span><span class="nx">options</span><span class="p">))</span> <span class="o">||</span>
        <span class="p">(</span><span class="k">await</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nx">destination_from_service_1</span><span class="p">.</span><span class="nx">getDestinationFromDestinationService</span><span class="p">)(</span><span class="nx">options</span><span class="p">));</span>
    <span class="k">return</span> <span class="nx">destination</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p><code class="language-plaintext highlighter-rouge">destination-cache</code> underlying is using <code class="language-plaintext highlighter-rouge">cache</code> with fixed 5 mins as expiration time, however, please note that the in-memory cache implementation does not support eviction, so it’s important to keep in mind not to cache objects unlimitedly, otherwise it may cause OOM.</p>

<hr />
<h2 id="approuter-in-sap">Approuter in @sap</h2>

<h3 id="tldr-1">TL;DR</h3>

<ul>
  <li><strong>NO</strong> global cache, only user session level cache</li>
  <li>No option to enable/disable cache for destination in <code class="language-plaintext highlighter-rouge">xs-app.json</code></li>
  <li>Destination Service in PROD has near half request come from approuter</li>
</ul>

<hr />

<p><code class="language-plaintext highlighter-rouge">approuter</code> is using a totally different approach to retrieve destination as above, here is the simplified sequential diagram:</p>

<p><img src="/assets/images/posts/2023-05-04/2.jpg" alt="" /></p>

<p><code class="language-plaintext highlighter-rouge">destination-token-middleware.getCacheDestination</code> is getting cached destination from user session, here is the code:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">getCachedDestination</span><span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">key</span><span class="p">,</span> <span class="nx">destinationName</span><span class="p">){</span>
  <span class="kd">let</span> <span class="nx">destination</span> <span class="o">=</span> <span class="nx">req</span><span class="p">.</span><span class="nx">session</span> <span class="o">&amp;&amp;</span> <span class="nx">req</span><span class="p">.</span><span class="nx">session</span><span class="p">.</span><span class="nx">user</span> <span class="o">&amp;&amp;</span> <span class="nx">req</span><span class="p">.</span><span class="nx">session</span><span class="p">.</span><span class="nx">user</span><span class="p">.</span><span class="nx">destinations</span> <span class="o">&amp;&amp;</span> <span class="nx">req</span><span class="p">.</span><span class="nx">session</span><span class="p">.</span><span class="nx">user</span><span class="p">.</span><span class="nx">destinations</span><span class="p">[</span><span class="nx">key</span><span class="p">];</span>
  <span class="k">if</span> <span class="p">(</span><span class="nx">destination</span> <span class="o">&amp;&amp;</span> <span class="p">((</span><span class="nx">destination</span><span class="p">.</span><span class="nx">destinationConfiguration</span><span class="p">.</span><span class="nx">authentication</span> <span class="o">===</span> <span class="dl">'</span><span class="s1">BasicAuthentication</span><span class="dl">'</span>
      <span class="o">||</span> <span class="nx">destination</span><span class="p">.</span><span class="nx">destinationConfiguration</span><span class="p">.</span><span class="nx">authentication</span> <span class="o">===</span> <span class="dl">'</span><span class="s1">NoAuthentication</span><span class="dl">'</span><span class="p">)</span> <span class="o">||</span>
      <span class="p">(</span><span class="nx">destination</span><span class="p">.</span><span class="nx">expireDate</span> <span class="o">&amp;&amp;</span> <span class="nx">destination</span><span class="p">.</span><span class="nx">expireDate</span> <span class="o">-</span> <span class="nb">Date</span><span class="p">.</span><span class="nx">now</span><span class="p">()</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">))){</span>
    <span class="kd">const</span> <span class="nx">logger</span>  <span class="o">=</span> <span class="nx">req</span><span class="p">.</span><span class="nx">loggingContext</span><span class="p">.</span><span class="nx">getLogger</span><span class="p">(</span><span class="dl">'</span><span class="s1">/Destination service</span><span class="dl">'</span><span class="p">);</span>
    <span class="nx">logger</span><span class="p">.</span><span class="nx">info</span><span class="p">(</span><span class="dl">'</span><span class="s1">Destination </span><span class="dl">'</span> <span class="o">+</span> <span class="nx">destinationName</span> <span class="o">+</span> <span class="dl">'</span><span class="s1"> has been retrieved from cache</span><span class="dl">'</span><span class="p">);</span>
    <span class="k">return</span> <span class="nx">destination</span><span class="p">;</span>
  <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="k">return</span> <span class="kc">null</span><span class="p">;</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Despite this, there is no other place in the request flow will cache the destination instance currently, which means each request from different user will result in a call to DestinationService, thus we did a check of backtrace in dynatrace, and found that the result proved the assumption:</p>

<p>BackTrace for DestinationService in DEV:</p>

<p><img src="/assets/images/posts/2023-05-04/3.jpg" alt="" /></p>

<p>BackTrace for DestinationService in PROD:</p>

<p><img src="/assets/images/posts/2023-05-04/4.jpg" alt="" /></p>

<hr />
<h3 id="more-findings">More findings</h3>
<p>Approuter supports integrate with <code class="language-plaintext highlighter-rouge">HTML5 Application Repository</code>, where we can change routes dynamically in runtime without redeploy approuter to make changes on <code class="language-plaintext highlighter-rouge">xs-app.json</code> work, the configuration supports global cache and by default cache expiration time is 5 mins. Detailed logic can be found in <code class="language-plaintext highlighter-rouge">dynamic-routing-util</code>, documentation can be found in <code class="language-plaintext highlighter-rouge">@sap/approuter - README.md</code>.</p>

<p>For schema of <code class="language-plaintext highlighter-rouge">xs-app.json</code> we can find from <code class="language-plaintext highlighter-rouge">xs-app-schema.json</code>.</p>]]></content><author><name>Leo</name><email>mail@nleo.me</email></author><category term="en" /><summary type="html"><![CDATA[Connectivity in @sap-cloud-sdk]]></summary></entry><entry><title type="html">Problems regarding so-called ‘Big Key’ in redis</title><link href="https://nleo.me/en/2023/04/22/bigkey_in_redis.html" rel="alternate" type="text/html" title="Problems regarding so-called ‘Big Key’ in redis" /><published>2023-04-22T13:11:35+00:00</published><updated>2023-04-22T13:11:35+00:00</updated><id>https://nleo.me/en/2023/04/22/bigkey_in_redis</id><content type="html" xml:base="https://nleo.me/en/2023/04/22/bigkey_in_redis.html"><![CDATA[<h3 id="big-key-definition">Big Key Definition</h3>

<p>Basically key is considered as big key if it has either too much memory usage or too many elements.</p>

<ul>
  <li>A STRING key whose size of value is 5 MB (the data is too large).</li>
  <li>A LIST key with 20,000 elements (the number of elements in the list is excessive).</li>
  <li>A ZSET key with 10,000 members (the number of members is excessive).</li>
  <li>A HASH key whose size is 100MB even if only contains 1,000 members (the size of the key is too large).</li>
</ul>

<p>It should be noted that the definition of Big Key might be different according to actual use cases and business scenarios of Redis. This is to say that you should judge taking all factors into consideration.<sup id="fnref:fn3" role="doc-noteref"><a href="#fn:fn3" class="footnote" rel="footnote">1</a></sup></p>

<h3 id="discover-big-keys">Discover Big Keys</h3>

<ol>
  <li>Use <code class="language-plaintext highlighter-rouge">redis-cli --bigkeys</code> or <code class="language-plaintext highlighter-rouge">redis-cli --memkeys</code> to detect big keys <sup id="fnref:fn1" role="doc-noteref"><a href="#fn:fn1" class="footnote" rel="footnote">2</a></sup></li>
  <li>Use <code class="language-plaintext highlighter-rouge">memory usage &lt;key&gt;</code> to find the memory usage of speficied key, careful when using in production environment as it may block other commands<sup id="fnref:fn2" role="doc-noteref"><a href="#fn:fn2" class="footnote" rel="footnote">3</a></sup></li>
</ol>

<h3 id="typical-problems">Typical Problems</h3>

<ul>
  <li>
    <p><strong>Execution slower</strong>: command executed much slower than others<sup id="fnref:fn4" role="doc-noteref"><a href="#fn:fn4" class="footnote" rel="footnote">4</a></sup>, typically the execution time should under 1ms, and the default slowlog config is 10ms. Slow execution may block other cmds and even result in timeout for clients.</p>
  </li>
  <li>
    <p><strong>Key eviction</strong>: if maxmemory and eviction policy is set, big keys get evicted(depends on the policy) which need much time to re-fill cache later</p>
  </li>
  <li>
    <p><strong>Network latency</strong>: if big key is frequently queried by clients, it will cause a significant amount of network traffic and may result in network congestion</p>
  </li>
  <li>
    <p><strong>Backup impact</strong>: AOF in redis has three modes of persistence: no, everysec, always. <sup id="fnref:fn5" role="doc-noteref"><a href="#fn:fn5" class="footnote" rel="footnote">5</a></sup> In ‘always’ mode, redis main thread will wait until fsync completed, big key will result in much more blocking time <sup id="fnref:fn7" role="doc-noteref"><a href="#fn:fn7" class="footnote" rel="footnote">6</a></sup> (however, ‘always’ is not a default nor a recommended config, it shouldn’t be a problem in most cases)</p>
  </li>
  <li>
    <p><strong>Read/Write skew</strong>: in redis cluster, keys are sharded in different nodes, frequent read/write to big keys may result in unbalanced resource usage, which means some nodes may have much higher work load</p>
  </li>
</ul>

<h3 id="appendix">Appendix</h3>

<p>Two kinds of object encoding for HASH: ziplist(listpack), hashtable. <sup id="fnref:fn6" role="doc-noteref"><a href="#fn:fn6" class="footnote" rel="footnote">7</a></sup></p>

<p>Use <code class="language-plaintext highlighter-rouge">object encoding &lt;key&gt;</code> to detect the actual encoding type.`</p>

<p>In general, ziplist or listpack is more memory efficient than hashtable but the time complexity for example <code class="language-plaintext highlighter-rouge">HGET</code>, <code class="language-plaintext highlighter-rouge">HSET</code> is O(n), since the elements size is limited, it won’t cause performance issue, however, as the size grows the time complexity will not acceptable or as the entries exceeds memory limit than the compression will not bring much benefits any more.</p>

<h3 id="references">References</h3>
<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:fn3" role="doc-endnote">
      <p>https://www.alibabacloud.com/blog/a-detailed-explanation-of-the-detection-and-processing-of-bigkey-and-hotkey-in-redis_598143 <a href="#fnref:fn3" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:fn1" role="doc-endnote">
      <p>https://redis.io/docs/ui/cli/#scanning-for-big-keys <a href="#fnref:fn1" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:fn2" role="doc-endnote">
      <p>https://redis.io/commands/memory-usage/ <a href="#fnref:fn2" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:fn4" role="doc-endnote">
      <p>https://developer.redis.com/operate/redis-at-scale/observability/identifying-issues/ <a href="#fnref:fn4" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:fn5" role="doc-endnote">
      <p>https://redis.io/docs/management/persistence/ <a href="#fnref:fn5" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:fn7" role="doc-endnote">
      <p>https://twitter.com/alexxubyte/status/1571880260177907713?lang=en <a href="#fnref:fn7" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:fn6" role="doc-endnote">
      <p>https://redis.com/ebook/part-2-core-concepts/01chapter-9-reducing-memory-use/9-1-short-structures/9-1-1-the-ziplist-representation/ <a href="#fnref:fn6" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Leo</name><email>mail@nleo.me</email></author><category term="en" /><summary type="html"><![CDATA[Big Key Definition]]></summary></entry><entry><title type="html">Analyze Deadlock in Activiti/Flowable</title><link href="https://nleo.me/en/2022/12/08/flowable_deadlock.html" rel="alternate" type="text/html" title="Analyze Deadlock in Activiti/Flowable" /><published>2022-12-08T09:08:32+00:00</published><updated>2022-12-08T09:08:32+00:00</updated><id>https://nleo.me/en/2022/12/08/flowable_deadlock</id><content type="html" xml:base="https://nleo.me/en/2022/12/08/flowable_deadlock.html"><![CDATA[<h2 id="what-is-deadlock">What is Deadlock?</h2>

<p>Most of us should hear about deadlock in operating system for the first time, it’s a situation when several processes hold and wait for more resources mutually, there are four prerequisites:</p>

<ol>
  <li>Mutual exclusion</li>
  <li>Hold and wait</li>
  <li>No preemption</li>
  <li>Circular wait</li>
</ol>

<p>Hence, deadlock is usually handled by preventing one of the four conditions listed above, the major approaches are as follows:</p>

<ul>
  <li>Deadlock avoidance</li>
  <li>Deadlock prevention</li>
  <li>Deadlock detection</li>
</ul>

<p>Deadlock avoidance looks similar to prevention, but they actually handle deadlock in different ways. Deadlock Prevention works by preventing any one of the four conditions from occuring, while Deadlock Avoidance works by analyzing if the system is safety when allocating resources, the most famous deadlock avoidance algorithm is Banker’s Algorithm. Deadlock Detection allows deadlock to occur, but it will detect the system state to check if there is deadlock, once deadlock detected, it will abort one of more involved processes. Despite process termination, other systems may use resource preemption to break the deadlock.</p>

<h2 id="deadlock-in-database">Deadlock in Database</h2>

<p>Deadlock Detection is widely used in database system, it tracks resource allocation and transaction state, if deadlock is detected, it will rollback and restart one of the transactions in order to break the cycle. Here we will use MySQL InnoDB as the target database system, and investigate the root cause of deadlock in database.</p>

<h4 id="transaction-in-mysql-innodb">Transaction in MySQL InnoDB</h4>

<p>When we talk about DB transaction, we all know that it is used to group several statements to perform atomically, there are four properties of transaction as atomicity, consistency, isolation and duration. Here we need to understand more about transaction isolation level, as transaction can be either a read transaction or a write transaction, different isolation level will make transaction behave differently. As described by SQL:1992 standard, there are four isolation levels:</p>

<ol>
  <li>Read uncommitted - the lowest isolation level, it allows dirty read which means a read transaction can see the not-yet-committed changes made by other transactions</li>
  <li>Read committed - stricter than the above one, a read transaction can only see committed changes made by others, however it doesn’t guarantee the same data will be consistent when reading repeatedly as other transaction may commit data change concurrently</li>
  <li>Repeatable read - to avoid non-repeatable read as described above, but this level doesn’t guarantee data consistency when write transaction doing insert or delete concurrently which is known as phantom read</li>
  <li>Serializable - the strictest isolation level, even phantom read is not allowed, read transaction and write transaction shall execute in serial</li>
</ol>

<p>Obiviously isolation levels define the behaviors of read transaction, but actually when implementing UPDATE and DELETE statement with conditions, they are also slightly affected with different locking strategy, we will discuss it in the next paragraph. Here we will focus on two important kinds of read in MySQL InnoDB: 1) consistent non-locking read; 2) locking read. And how they are implemented in InnoDB.</p>

<ul>
  <li>
    <p>Consistent Non-locking Read: it is based on MVCC and does not acquire lock but reads a snapshot based on the version of current transaction. In read committed, each read within the same transaction will get its own snapshot while repeatable read will get the snapshot established by the first read for other same reads within the transaction. In this case, unrepeatable read and phantom read are both avoided when using repeatable read, but here note that even SELECT statement follows consistent read, UPDATE and DELETE statement behave differently, once another transaction committed the changes to some rows that current transaction updated or deleted, those changes will be visible to current transaction.</p>
  </li>
  <li>
    <p>Locking Read: it will acquire necessary lock by using sql like <code class="language-plaintext highlighter-rouge">SELECT ... FOR UPDATE</code> and <code class="language-plaintext highlighter-rouge">SELECT ... LOCK IN SHARE MODE</code>, the former will acquire exclusive lock while the latter only requests shared lock so that other read transactions can also perform select, if you don’t want the statement to be blocked, you can add NOWAIT or SKIP LOCKED at the end. In read committed, it will acquire record lock on matching records, but gap lock is not acquired and phantom row problem may occur. In repeatable read locking depends on the search condition, gap lock or next-key lock may need if it’s not a unique search with a unique index. In serializable isolation level simple SELECT statement will be automatically converted to shared blocking read when autocommit is disabled.</p>
  </li>
</ul>

<h4 id="locking-in-mysql-innodb">Locking in MySQL InnoDB</h4>

<p>Lock is used to provide data consistency in concurrent computing, based on different types of object to be locked, there are three typical granularities of lock:</p>

<ol>
  <li>Table lock - lowest lock overhead but minimum concurrency</li>
  <li>Page lock - page is the storage unit of underlying file system, used in MySQL BDB engine</li>
  <li>Record lock - or known as row lock, the finest granularity of lock</li>
</ol>

<p>Table locks in InnoDB can be divided into three types: 1) explicit table lock; 2) intention lock; 3) AUTO-INC lock. Explicit table lock can be acquired and released with statement <code class="language-plaintext highlighter-rouge">LOCK TABLES...(READ/WRITE)</code> and <code class="language-plaintext highlighter-rouge">UNLOCK TABLES</code>. Intention lock will be implicitly acquired when you performing locking read or INSERT/UPDATE/DELETE, note that only <code class="language-plaintext highlighter-rouge">SELECT ... FOR SHARE</code> will acquire intention shared lock and others will acquire intention exclusive lock. AUTO-INC lock is used when doing insert with auto increment columns, however, this lock is different than others, it’s a short-lived lock and may release ASAP instead of transaction end. These table locks compatibility can be summarized as:</p>
<style scoped="">
table th:first-of-type {
    width: 30%;
}
table th:nth-of-type(2) {
    width: 10%;
}
table th:nth-of-type(3) {
    width: 10%;
}
table th:nth-of-type(4) {
    width: 15%;
}
table th:nth-of-type(5) {
    width: 15%;
}
table th:nth-of-type(6) {
    width: 20%;
}
</style>

<table>
  <thead>
    <tr>
      <th>request\hold</th>
      <th style="text-align: center">S</th>
      <th style="text-align: center">X</th>
      <th style="text-align: center">IS</th>
      <th style="text-align: center">IX</th>
      <th style="text-align: center">AUTO-INC</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>S</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">⛔️</td>
    </tr>
    <tr>
      <td>X</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">⛔️</td>
    </tr>
    <tr>
      <td>IS</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">✅</td>
    </tr>
    <tr>
      <td>IX</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">✅</td>
    </tr>
    <tr>
      <td>AUTO-INC</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">⛔️</td>
    </tr>
  </tbody>
</table>

<p>Row locks in InnoDB can be simplified into: 1) record lock, which is shorted as REC_NOT_GAP, typically used for unique search condition on a unique index; 2) gap lock, a lock on the gap between index records, can co-exist with no matter shared or exclusive, typically used when it’s a range search condition or the index is not a unique one; 3) next-key lock, which is actually a combination of record lock and gap lock, depends on whether the range search is inclusive; 4) insert intention lock, another kind of gap lock, used when doing insertion, cannot co-exist with gap lock. These record locks compatibility can be given as a matrix as well:</p>
<style scoped="">
table th:first-of-type {
    width: 17%;
}
table th:nth-of-type(2) {
    width: 14%;
}
table th:nth-of-type(3) {
    width: 14%;
}
table th:nth-of-type(4) {
    width: 10%;
}
table th:nth-of-type(5) {
    width: 14%;
}
table th:nth-of-type(6) {
    width: 14%;
}
table th:nth-of-type(7) {
    width: 17%;
}
table {
  font-size: 0.6rem;
}
</style>

<table>
  <thead>
    <tr>
      <th style="text-align: center">request\hold</th>
      <th style="text-align: center">S, REC_NOT_GAP</th>
      <th style="text-align: center">X, REC_NOT_GAP</th>
      <th style="text-align: center">*, GAP</th>
      <th style="text-align: center">S (next-key)</th>
      <th style="text-align: center">X (next-key)</th>
      <th style="text-align: center">*, INSERT_INTENTION</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: center">S, REC_NOT_GAP</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">✅</td>
    </tr>
    <tr>
      <td style="text-align: center">X, REC_NOT_GAP</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">✅</td>
    </tr>
    <tr>
      <td style="text-align: center">*, GAP</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">✅</td>
    </tr>
    <tr>
      <td style="text-align: center">S (next-key)</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">⛔️</td>
    </tr>
    <tr>
      <td style="text-align: center">X (next-key)</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">⛔️</td>
    </tr>
    <tr>
      <td style="text-align: center">*, INSERT_INTENTION</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">✅</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">⛔️</td>
      <td style="text-align: center">✅</td>
    </tr>
  </tbody>
</table>

<p>Here are some points need to pay attention:</p>

<ol>
  <li>the compatibility matrix is asymmetric, to be more specific, insert intention lock has to wait for gap lock but gap lock doesn’t need to wait for insert intention lock</li>
  <li>a shared lock on the index record will be acquired when duplicate key error occurs, which could result in deadlock in some extreme case, for example: if table t_test contains value id=1, SessionA begins tx and delete id=1, SessionB begins tx and insert id=1, SessionC begins tx and insert id=1, SessionA will held a exclusive record lock for id=1, SessionB and SessionC will both waiting for a shared record lock on id=1 as they are faing duplicate key error, after SessionA commits tx, there will be deadlock because SessionB and SessionC are holding shared record lock and trying to request exclusive record lock on id=1</li>
  <li>if a unique secondary index is used, matching primary index record will also be locked (which differs from the conclusion from [10])</li>
  <li>if UPDATE modifies primary index records, implicit shared record locks on affected secondary index records will be held</li>
  <li>a next-key lock will be acquired when the search condition does not fully qualified the using composite index</li>
  <li>foreign key constraint will acquire shared record lock on those records to be checked when performing INSERT/UPDATE/DELETE</li>
</ol>

<h2 id="deadlock-in-activitiflowable">Deadlock in Activiti/Flowable</h2>

<p>Finally, we come to our topic, deadlock is a known issue for Activiti and forked projects like Flowable and Camunda, here is Activiti issue, Camunda issue, Flowable issue. We also received several jira issues regarding deadlock like PFS-7154, PFS-9367.</p>

<p>To be frank, it’s hard to list cases or patterns for all the deadlocks in these workflow engines, even we narrow down the scope to one workflow engine, they may have different tables, columns, indexes, constraints among different versions, not to mention different underlying database systems use different locking strategy when performing DML/DDL, I would recommend to take a look into the deadlock graph to figure out the exact root cause when facing such kind of issue in production, here I will take Flowable 6.7 and MySQL8.0(innoDB engine) as example.</p>

<p>Let’s first have a brief look of the implementation of Flowable 6.7(the relevant code doesn’t vary a lot from Activiti and Camunda) We all knew that the underlying persistence layer for Flowable is MyBatis, to reduce unnecessary write and read operations to DB, Flowable provided DbSqlSession to perform CRUD and once the command ended it will flush changed objects to DB when required:
<img src="/assets/images/posts/2022-12-08/1.jpg" alt="1" /></p>

<p><img src="/assets/images/posts/2022-12-08/2.jpg" alt="2" /></p>

<p>Now take a look at how DbSqlSession interact with MyBatis to execute statements: 
<img src="/assets/images/posts/2022-12-08/3.jpg" alt="3" /></p>

<p>You could find the execution sequence of write statements: 1) update with parameters; 2) insert; 3) update with entities; 4) delete with entities; 5) delete with parameters. BTW, I think it’s a potential defect to defer the No.5 operation, as select could read stale objects which shall be deleted earlier even within the same transaction.</p>

<p>I do believe most deadlock cases are caused by updates/deletes especially updates, the most important thing is the operation order strategy of Flowable:</p>

<ol>
  <li>for updates, the relative order of entity class may be different as EntityCache is using Class as the key, the hash code for same class is different in different nodes</li>
  <li>for both updates and deletes, Flowable did not sort the entities by id at all, which means different nodes could write same entities in different order and very likely to result in deadlock</li>
</ol>

<p>What about insert? Flushing inserts is obeying the order of class and time sequence(first insert first flush), and remember INSERT_INTENTION does not block gap lock and other INSERT_INTENTION unless you are inserting same ID_, so it shouldn’t be a main reason for deadlock as well. (Though deadlock could happen in some case, as Flowable is using String as the type of ID, and the value can be self assigned in the code, if txA is inserting Entity1 and txB is inserting Entity2, both succeeded, and then txA try to insert Entity2 while txB try to insert Entity1, then deadlock will occur)</p>

<p>Another two conditional write operations: No.1 - update with parameters and No.5 - delete with parameters, it’s impossible to predict the actual affected rows, so the only way to avoid them from deadlock is restrict the data set and make the operation as simple as possible, for example do not call one command inside another command, add distinctive index for related columns. The good news is that currently the most two typical cases for conditonal updates are: 1) migrate tenant id; 2) update lock info for jobs and process instances. Case1 is rare without doubt, and case2 has two situations, one is clear process instances’ lock when engine shutting down, another is release jobs’ lock periodically, both are cheap operation and the dataset is always restricted to exact lock owner.</p>

<p>Here I didn’t mention select specifically, as select in Flowable is always non-blocking which couldn’t cause deadlock unless you change the default isolation level to serializable.</p>

<h2 id="one-deadlock-example">One Deadlock Example</h2>

<p>As I mentioned in the above section, EntityCache is using Class as the key of HashMap, when two or more nodes are performing update/delete on same objects, it will be possible to build a cycle, and the possibility will be larger if more classes involved. (Given two nodes, if three classes involved, it will be 1/6 to have the same order, in another word, 5/6 to have different order, when four classes involved, the possibility will be 23/24)</p>

<p>In my example, I simply invoked dbSqlSession.update in the command, with four classes and each class has 10 entities, run the test code in both gradle and junit to simulate two nodes.
<img src="/assets/images/posts/2022-12-08/4.png" alt="4" /></p>

<p>The test result shows that one test succeeded and another failed with deadlock:
<img src="/assets/images/posts/2022-12-08/5.png" alt="5" /></p>

<p>Let’s take a look at the deadlock graph, since I am using MySQL, we can use SHOW ENGINE INNODB STATUS command to show latest detected deadlock details:</p>

<div class="language-zsh highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">***</span> <span class="o">(</span>1<span class="o">)</span> TRANSACTION:
TRANSACTION 3059, ACTIVE 0 sec starting index <span class="nb">read
</span>mysql tables <span class="k">in </span>use 1, locked 1
LOCK WAIT 4 lock struct<span class="o">(</span>s<span class="o">)</span>, heap size 1128, 10 row lock<span class="o">(</span>s<span class="o">)</span>, undo log entries 9
MySQL thread <span class="nb">id </span>329, OS thread handle 123145369366528, query <span class="nb">id </span>4634 localhost 127.0.0.1 root updating
/<span class="k">*</span> <span class="nv">APPLICATIONUSER</span><span class="o">=</span>pepsico, <span class="nv">APPLICATION</span><span class="o">=</span>sflow-integration-test <span class="k">*</span>/ update PEPSICO.ACT_RU_JOB
         SET REV_ <span class="o">=</span> 7,
            
            
            
                CATEGORY_ <span class="o">=</span> <span class="s1">'fb8dcb7c-c095-45a0-a9bb-1485f85a72e5'</span>,
            
            
            
                RETRIES_ <span class="o">=</span> 0 
        where <span class="nv">ID_</span><span class="o">=</span> <span class="s1">'job2'</span>
        and REV_ <span class="o">=</span> 6

<span class="k">***</span> <span class="o">(</span>1<span class="o">)</span> HOLDS THE LOCK<span class="o">(</span>S<span class="o">)</span>:
RECORD LOCKS space <span class="nb">id </span>92 page no 4 n bits 96 index PRIMARY of table <span class="sb">`</span>pepsico<span class="sb">`</span>.<span class="sb">`</span>act_ru_variable<span class="sb">`</span> trx <span class="nb">id </span>3059 lock_mode X locks rec but not gap
Record lock, heap no 2 PHYSICAL RECORD: n_fields 17<span class="p">;</span> compact format<span class="p">;</span> info bits 0
 0: len 4<span class="p">;</span> hex 76617231<span class="p">;</span> asc var1<span class="p">;;</span>
 1: len 6<span class="p">;</span> hex 000000000bf3<span class="p">;</span> asc       <span class="p">;;</span>
 2: len 7<span class="p">;</span> hex 01000001001256<span class="p">;</span> asc       V<span class="p">;;</span>
 3: len 4<span class="p">;</span> hex 80000007<span class="p">;</span> asc     <span class="p">;;</span>
 4: len 6<span class="p">;</span> hex 737472696e67<span class="p">;</span> asc string<span class="p">;;</span>
 5: len 30<span class="p">;</span> hex 66623864636237632d633039352d343561302d613962622d313438356638<span class="p">;</span> asc fb8dcb7c-c095-45a0-a9bb-1485f8<span class="p">;</span> <span class="o">(</span>total 36 bytes<span class="o">)</span><span class="p">;</span>

Too long, other Record locks on the same table omitted...
 

<span class="k">***</span> <span class="o">(</span>1<span class="o">)</span> WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space <span class="nb">id </span>88 page no 4 n bits 96 index PRIMARY of table <span class="sb">`</span>pepsico<span class="sb">`</span>.<span class="sb">`</span>act_ru_job<span class="sb">`</span> trx <span class="nb">id </span>3059 lock_mode X locks rec but not gap waiting
Record lock, heap no 13 PHYSICAL RECORD: n_fields 29<span class="p">;</span> compact format<span class="p">;</span> info bits 0
 0: len 4<span class="p">;</span> hex 6a6f6232<span class="p">;</span> asc job2<span class="p">;;</span>
 1: len 6<span class="p">;</span> hex 000000000bf2<span class="p">;</span> asc       <span class="p">;;</span>
 2: len 7<span class="p">;</span> hex 02000001420823<span class="p">;</span> asc     B <span class="c">#;;</span>
 3: len 4<span class="p">;</span> hex 80000007<span class="p">;</span> asc     <span class="p">;;</span>
 4: len 30<span class="p">;</span> hex 61313136636161332d323565312d346436622d383535662d336537646235<span class="p">;</span> asc a116caa3-25e1-4d6b-855f-3e7db5<span class="p">;</span> <span class="o">(</span>total 36 bytes<span class="o">)</span><span class="p">;</span>
 5: len 1<span class="p">;</span> hex 32<span class="p">;</span> asc 2<span class="p">;;</span>


<span class="k">***</span> <span class="o">(</span>2<span class="o">)</span> TRANSACTION:
TRANSACTION 3058, ACTIVE 0 sec starting index <span class="nb">read
</span>mysql tables <span class="k">in </span>use 1, locked 1
LOCK WAIT 6 lock struct<span class="o">(</span>s<span class="o">)</span>, heap size 1128, 19 row lock<span class="o">(</span>s<span class="o">)</span>, undo log entries 18
MySQL thread <span class="nb">id </span>349, OS thread handle 123145399185408, query <span class="nb">id </span>4641 localhost 127.0.0.1 root updating
/<span class="k">*</span> <span class="nv">APPLICATIONUSER</span><span class="o">=</span>pepsico, <span class="nv">APPLICATION</span><span class="o">=</span>sflow-integration-test <span class="k">*</span>/ update PEPSICO.ACT_RU_VARIABLE
         SET REV_ <span class="o">=</span> 7,
            
                NAME_ <span class="o">=</span> <span class="s1">'a116caa3-25e1-4d6b-855f-3e7db5810dc1'</span>,
            
            
            
            
            
            
            
                TYPE_ <span class="o">=</span> <span class="s1">'string'</span> 
        where ID_ <span class="o">=</span> <span class="s1">'var9'</span>
        and REV_ <span class="o">=</span> 6

<span class="k">***</span> <span class="o">(</span>2<span class="o">)</span> HOLDS THE LOCK<span class="o">(</span>S<span class="o">)</span>:
RECORD LOCKS space <span class="nb">id </span>88 page no 4 n bits 96 index PRIMARY of table <span class="sb">`</span>pepsico<span class="sb">`</span>.<span class="sb">`</span>act_ru_job<span class="sb">`</span> trx <span class="nb">id </span>3058 lock_mode X locks rec but not gap

Record lock, heap no 13 PHYSICAL RECORD: n_fields 29<span class="p">;</span> compact format<span class="p">;</span> info bits 0
 0: len 4<span class="p">;</span> hex 6a6f6232<span class="p">;</span> asc job2<span class="p">;;</span>
 1: len 6<span class="p">;</span> hex 000000000bf2<span class="p">;</span> asc       <span class="p">;;</span>
 2: len 7<span class="p">;</span> hex 02000001420823<span class="p">;</span> asc     B <span class="c">#;;</span>
 3: len 4<span class="p">;</span> hex 80000007<span class="p">;</span> asc     <span class="p">;;</span>
 4: len 30<span class="p">;</span> hex 61313136636161332d323565312d346436622d383535662d336537646235<span class="p">;</span> asc a116caa3-25e1-4d6b-855f-3e7db5<span class="p">;</span> <span class="o">(</span>total 36 bytes<span class="o">)</span><span class="p">;</span>
 5: len 1<span class="p">;</span> hex 32<span class="p">;</span> asc 2<span class="p">;;</span>

Too long, other Record locks on the same table omitted...

<span class="k">***</span> <span class="o">(</span>2<span class="o">)</span> WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space <span class="nb">id </span>92 page no 4 n bits 96 index PRIMARY of table <span class="sb">`</span>pepsico<span class="sb">`</span>.<span class="sb">`</span>act_ru_variable<span class="sb">`</span> trx <span class="nb">id </span>3058 lock_mode X locks rec but not gap waiting
Record lock, heap no 30 PHYSICAL RECORD: n_fields 17<span class="p">;</span> compact format<span class="p">;</span> info bits 0
 0: len 4<span class="p">;</span> hex 76617239<span class="p">;</span> asc var9<span class="p">;;</span>
 1: len 6<span class="p">;</span> hex 000000000bf3<span class="p">;</span> asc       <span class="p">;;</span>
 2: len 7<span class="p">;</span> hex 01000001001016<span class="p">;</span> asc        <span class="p">;;</span>
 3: len 4<span class="p">;</span> hex 80000007<span class="p">;</span> asc     <span class="p">;;</span>
 4: len 6<span class="p">;</span> hex 737472696e67<span class="p">;</span> asc string<span class="p">;;</span>
 5: len 30<span class="p">;</span> hex 66623864636237632d633039352d343561302d613962622d313438356638<span class="p">;</span> asc fb8dcb7c-c095-45a0-a9bb-1485f8<span class="p">;</span> <span class="o">(</span>total 36 bytes<span class="o">)</span><span class="p">;</span>
</code></pre></div></div>

<p>We could see that tx1 is holding X, REC_NOT_GAP on var1~var9 and waiting for lock on job2, while tx2 is holding X, REC_NOT_GAP on job1~job9 and waiting for lock on var9, which perfectly result in a circular wait status. To fix deadlock in this case is not complex, we just need to keep the order by entity class and entity id, so we can directly re-implement the EntityCache.getAllCachedEntities.</p>

<p>However, this is not the final solution, remember that Flowable is flushing entities by operation(INSERT/UPDATE/DELETE), which means we need to rewrite the strategy of DbSqlSession.flush, this is a big code change and we will have a try in the future.</p>

<h2 id="references">References</h2>
<ol>
  <li><a href="https://en.wikipedia.org/wiki/Deadlock">Deadlock</a></li>
  <li><a href="https://www.geeksforgeeks.org/difference-between-deadlock-prevention-and-deadlock-avoidance/">Difference between Deadlock Prevention and Deadlock Avoidance</a></li>
  <li><a href="https://en.wikipedia.org/wiki/Isolation_(database_systems)">Isolation(database systems)</a></li>
  <li><a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-transaction-isolation-levels.html">MySQL - Transaction Isolation Levels</a></li>
  <li><a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-locking.html">MySQL - InnoDB Locking</a></li>
  <li><a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-consistent-read.html">MySQL - Consistent Nonlocking Reads</a></li>
  <li><a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html">MySQL - Locking Reads</a></li>
  <li><a href="https://lynn-kwong.medium.com/understand-the-basics-of-locks-and-deadlocks-in-mysql-part-i-92f229db0a">Understand the basics of locks and deadlocks in MySQL</a></li>
  <li><a href="https://dev.mysql.com/blog-archive/innodb-data-locking-part-2-locks/">InnoDB Data Locking - Part 2 “Locks”</a></li>
  <li><a href="https://dev.mysql.com/blog-archive/innodb-data-locking-part-2-5-locks-deeper-dive/">InnoDB Data Locking - Part 2.5 “Locks” (Deeper dive)</a></li>
  <li><a href="https://dev.mysql.com/blog-archive/innodb-data-locking-part-3-deadlocks/">InnoDB Data Locking – Part 3 “Deadlocks”</a></li>
</ol>]]></content><author><name>Leo</name><email>mail@nleo.me</email></author><category term="en" /><summary type="html"><![CDATA[What is Deadlock?]]></summary></entry><entry><title type="html">Workflow微服务开发中的一致性问题</title><link href="https://nleo.me/cn/2022/10/22/workflow_consistency.html" rel="alternate" type="text/html" title="Workflow微服务开发中的一致性问题" /><published>2022-10-22T06:40:13+00:00</published><updated>2022-10-22T06:40:13+00:00</updated><id>https://nleo.me/cn/2022/10/22/workflow_consistency</id><content type="html" xml:base="https://nleo.me/cn/2022/10/22/workflow_consistency.html"><![CDATA[<p>一致性是分布式系统中常见的问题，大多数业务系统在CAP中都会选择AP而牺牲强一致性，workflow微服务也不例外，这篇文章想结合所开发的workflow微服务的两个典型的业务场景来聊一聊如何保障最终一致性。</p>

<h3 id="usertask操作的一致性">UserTask操作的一致性</h3>
<p>UserTask是审批流的核心组成部分，也是BPMN中最常见的task类型之一，用以表示需要人工介入的任务，一般需要支持claim，delegate，resolve，complete等操作以满足不同业务场景的需要，目前在我们的实际业务使用中仅支持complete操作，用户的通过或驳回操作底层都是调用complete只是传递不同的参数。
其核心组成有两大块：</p>
<ol>
  <li>user assignment，其中UserTask域只存储user id或group id，而用户域负责根据type和id进行解析；</li>
  <li>form，用户审批时一般在UI上需要展示相关信息，因此除了字段类型和数据之外还需要存储UI展示所需要的数据，与UI组件有一定的耦合。
目前我们线上的业务方使用场景如下图：</li>
</ol>

<p><img src="/assets/images/posts/2022-10-22/1.jpg" alt="2022101301 copy" /></p>

<p>这里可以看到有两个主要的业务场景：1）创建user task实例，需要通知下游Todo模块以保证相关用户可以收到提醒；2）用户完成user task，需要保证Todo被标记为已完成同时通知服务侧执行下一步。</p>

<p>第一个场景的业务为工作流走到userTask的时候执行对应的activityBehavior，根据userId查询candidate并创建task实例，并根据candidates到下游为每个candidate创建Todo，入口在服务侧，如果消息丢失则会导致相关用户收不到未做事项提醒从而导致流程卡住。
这里有一个注意点是下游在做幂等性消费的时候已完成的Todo也需要进行查询，否则可能出现这样一种情况：1. workflow service发送userTaskCreatedEvent(userTask:1, candidate:a)，2. 下游收到之后创建一条Todo(userTask:1,user:a,status:new)，发送确认消息但丢失或者延迟较大导致workflow service未收到，3. user: a审批完task之后Todo(userTask:1,user:a,status:done)，即软删除，4. workflow service重发userTaskCreatedEvent(userTask:1, candidate:a)，5. 下游收到之后根据userTask=1 and user=’a’ and isDeleted=0查询Todo返回空，再次创建一条Todo。</p>

<p>第二个场景的业务入口在单体系统中，对应的业务方还没有微服务化，逻辑上来说调用顺序应如：下游业务发送complete event-&gt;工作流微服务发送task completed event-&gt;Todo标记对应的数据为已完成。但从图上可以看到，Todo模块和下游业务方都在单体系统中，因此为了简化流程，我们将clear Todo和send complete event包装在一个transaction中，具体来说通过将event注册到synchronization上，等tx commit之后再发送event。
至于这里为什么要采用transactional event，是因为业务方在调用完complete task之后往往还有一些额外的操作，比如业务方自实现的状态保存，这些操作有可能会失败导致transaction回滚，如果不把event延迟到tx commit之后再提交，可能出现Todo因为tx rollback而没有清除但event已经发送出去导致服务侧的workflow已经将对应的userTask标记为completed。</p>

<p>可以注意到这里两个场景可以构成一个业务闭环，userTask从创建到完成每一次状态跃迁都是由event驱动，如图所示：</p>

<p><img src="/assets/images/posts/2022-10-22/3.jpg" alt="1" /></p>

<p>已知TaskCreated-&gt;TaskNotified的时候可能会出现消息丢失，因此我们会定时轮询状态为TaskCreated并且updated_at超出1min的进行消息重发，而TaskNotified-&gt;TaskCompleted也可能出现消息丢失，因为前文提到上游单体系统只是将event的发出时间推迟并没有保证消息不丢，因此在这种场景下，我们同样通过轮询状态为TaskNotified并且updated_at超出1d的task，然后到Todo侧查询是否存在未完成的Todo，如果存在意味着用户确实没有完成相应的task则将updated_at更新为current，如果不存在则说明用户已经完成操作，在workflow服务端将task complete从而保证流程能正常走下去。
至于为什么TaskCreated可以直接跃迁至TaskCompleted，是因为可能出现前文提到的Todo的确认消息丢失或者延迟，用户操作了complete，workflow服务在收到Todo确认之前先收到了complete task的消息，这种情况下也是可以直接将状态标记为completed。</p>

<h3 id="servicetask执行的一致性">ServiceTask执行的一致性</h3>
<p>ServiceTask是BPMN中常见的一种task类型，在内嵌式的业务编排工作流当中常被用做执行本地Java代码以满足业务扩展需求，但在微服务架构下业务代码分布在各个业务节点，flowable默认的实现很明显并不能满足我们的需求，为此我们提供了基于service query（读）和service command（写）的执行策略，当流程实例走到ServiceTask的时候会发送消息对应的topic，下游消费者订阅相关topic之后执行对应的业务代码并通过消息发送执行结果，服务侧会订阅该topic并根据返回结果是否出错决定走什么分支，整体流程如下：</p>

<p><img src="/assets/images/posts/2022-10-22/2.jpg" alt="2022101301" /></p>

<p>其中关于task的输入输出是另外一个大的话题，这里暂且不表，我们仅关注于跨节点可能引入的状态不一致问题。
与UserTask类似，一个完整的业务流程最终会走回服务侧，即ServiceTask执行的开始和结束都在workflow服务端，因此这里也是通过业务自查来保证task被下游执行。
我们在上游（即服务侧）引入本地数据库表，在TaskRequestProduer发送消息之前先将task的相关信息存入表中，状态标记成unfinished，下游收到消息之后根据实际业务场景做幂等处理，当然对于只读场景（上文提到的service query）则没有幂等性要求，下游完成task execution之后则会发送消息到服务侧，考虑到收到消息意味着要调用ServiceTaskActivityBehavior.trigger，此时服务侧会继续执行processInstance直到下一个async continuation才会停止，意味着此刻才会提交topic partition offset，这个时间是不固定的，因此我们在consumer中做了异步trigger，具体来说会将其存成job同时把task表中的数据标记成finished，job后续会被asyncExecutor获取并执行，这里多说一句，job的获取绝大多数情况都是通过TransactionSynchronization注册到当前事务，在afterCommit会直接提交到asyncExecutor执行，避免轮询。除此之外，服务侧每个节点都会有后台线程定时检查超时未完成的task record，若发现有这样的record则会重发消息。</p>

<h3 id="小结">小结</h3>
<p>与RocketMQ的事务消息相比，虽然本地消息表的性能会差一大截，但考虑到我们的业务场景消息量并不算大，根据旧系统的数据估算，单个DC每天的消息量大约略高于100w，假设因为引入本地消息表导致的额外SQL性能消耗10ms，那么3台server只需要1h就能完成100w+的消息投递，因此对实际的业务并不会造成什么影响。
除此之外，仅仅在工作流服务侧通过RocketMQ保证消息不丢失还不够，下游在发送complete userTask或者返回serviceTask执行结果的时候也需要保证消息不能丢失，但由于我们的下游是单体系统，其消息中间件也是基于kafka，如果要在下游引入本地消息表，其开发成本也不低，因此相比较于RocketMQ，通过引入中间状态和本地消息表来实现事务一致性更适合我们的业务场景。</p>]]></content><author><name>Leo</name><email>mail@nleo.me</email></author><category term="cn" /><summary type="html"><![CDATA[一致性是分布式系统中常见的问题，大多数业务系统在CAP中都会选择AP而牺牲强一致性，workflow微服务也不例外，这篇文章想结合所开发的workflow微服务的两个典型的业务场景来聊一聊如何保障最终一致性。]]></summary></entry><entry><title type="html">这三年</title><link href="https://nleo.me/cn/2022/10/12/three_years_exp.html" rel="alternate" type="text/html" title="这三年" /><published>2022-10-12T08:42:33+00:00</published><updated>2022-10-12T08:42:33+00:00</updated><id>https://nleo.me/cn/2022/10/12/three_years_exp</id><content type="html" xml:base="https://nleo.me/cn/2022/10/12/three_years_exp.html"><![CDATA[<p>是很久没有写文章了，提笔的习惯一旦落下一时半会就很难再捡起来，仔细想想可能是因为三年前跳槽去某多多吧，工作忙起来确实没有精力再去整理自己的思路，虽说后面跑路回了外企却也是荒废掉了这个repo。最近工作上有不少感想，便想着在这里再写点东西，也不知道下一次断更会是什么时候，但愿不会太快。</p>

<h4 id="在杭州">在杭州</h4>
<p>19年年中的一个晚上，我刚面试完准备回杭州的住处，在空旷的虹桥高铁站我问我自己：真的想好要回上海了吗。</p>

<p>毕竟18年我是抱着一颗定居杭州的心从上海跳过去的，彼时杭州还是程序员的理想城市，至少对于当时的我来说是这样。然而随着贸易战影响渐显，而互联网业务开始遇冷，作为互联网一线城市的杭州也很快受到了影响，刚入职新东家一个多月的我第一次体会到了寒气——公司裁员。作为还在试用期的我理论上应该上裁员名单的，事实也确实如此，只是我当时的老板力保所以才幸免于难，当然这些是后来跟大老板聊天的时候得知的。</p>

<p>然而这件事在我这里并没有这么简单的就翻篇了，我开始思考这样的杭州是否真的适合我生活，或许25岁的我可以很快找好下家，裁员对于我来说可能并不会造成什么实质性的影响，但五年后呢，十年后呢，除去阿里、网易，杭州又能剩下多少工作机会，然而周围的房价却仍在节节攀升，在这种巨大的心理落差下我搁置了落户杭州的计划，重新开始着眼于上海的工作机会。</p>

<h4 id="回上海">回上海</h4>
<p>上海的房价比之杭州更甚，于是能开出double年包的某多多成了我的下一站。</p>

<p>忙、不规律是这里的常态，尤其是在接手了三个微服务项目之后，每天都有对不完的需求、响不停的警报，有的时候早上6点多就得起床到公司值早班，夜里3、4点会被告警电话call起来处理线上问题，每天最放松的时间大概就是午睡之后去楼下买咖啡的时候，因为那是一天当中为数不多的可以跟前女友在楼下见面的机会——是的，前女友也是某多多的。</p>

<p>但这里也很有趣，大家年龄相仿，兴趣相似，会聊游戏，会聊新显卡和CPU，会吐槽难吃的订餐，会在深夜加完班之后一起出去撸串，既是同事也是朋友。当然还有工作上的满足感，知道自己在做什么并为此感到骄傲——这是在外企很难获得的感受。
但某多也只是一个短暂的过客，19年年底老东家老板联系我说公司正在做微服务技术转型，希望我回去一起做出点新的东西，并表态薪水不会下降太多，这很难不心动，所以即使当时的老板和大老板都分别找我聊过许久也没能改变我回流的打算，于是就这样跟hr确定了20年年后入职。</p>

<h4 id="回流老东家">回流老东家</h4>
<p>很快新冠爆发了，虽然上海三月份就解封了，但公司允许回到办公室办公已经是好几个月之后的事情了，在那之前wfh成了新的工作常态，不，准确的说成了这两年多的工作常态。</p>

<p>外企的工作氛围虽不及互联网活跃，但见到老同事总归还是有不少话聊的，聊天中得知在我回来前的这段时间大家有尝试做一个新的支持扩展字段的ORM框架，这并不难理解，毕竟我们小组之前在旧的单体系统中也是做这个的，但说实话扩展字段有现成的轻量级的解决方案，为了这个重新开发一套新的数据访问层的库属实捡芝麻丢西瓜，不出意料在内部评审PoC的时候就被上海site的架构师否了。</p>

<p>其实当时我们有不少现成的业务可以做成微服务，比如规则引擎，工作流引擎，但很可惜虽然我提出了这些想法，由于组织架构划分的原因，我们组在德国的架构师更希望我们做一个跟过去职能相近的项目，很快做一个元数据服务的想法被提了出来，但可能是由于转型期，工作流程不够规范，在我们做出了PoC之后才发现这个项目竟然没有得到过PM的首肯，导致在上线前的评审中PM提出没有足够的商业价值，于是就这样我回来后的第一个项目搁浅了。</p>

<p>虽然前面提过自研一套支持扩展字段的ORM框架被否决了，但似乎德国的架构师并没有放弃这个想法，很快这个项目又重新被提起，这次不同的是不再从0开始自研，而是基于公司内部的低代码开发框架CDS包装一层，在调研过CDS之后我们决定裁减掉部分模块，底层的查询语言使用CDS提供的CQL，考虑到复杂度和扩展性，业务逻辑层我们希望由业务团队自行暴露REST API而不是使用CDL，不过这也导致我们跟德国的架构师理念有分歧，于是在PoC演示之后这个项目又一次不了了之。</p>

<p>时间很快来到了21年上半年，经历过两次项目失败之后组内已经有些灰心了，不过好消息是由于我们的争取，workflow被划到我们组，线上主要使用的场景有流程审批和业务编排，完全不缺下游业务和使用客户，于是我们收拾好心情准备大干一场。
很快我们调研了现有单体系统中的几个旧的实现，梳理好使用案例后我们决定先从审批流做起，一来当时刚好有另外一个业务团队提出需要接入审批流的微服务，二来审批流的复杂度相比较于业务编排更低。确定好方向之后我便开始对比几个开源工作流引擎如activiti、flowable、camunda等，最终我们选用了flowable作为我们底层引擎的实现，然后又花了一个月左右的时间开发出PoC并给老大们做了demo，效果很不错老大们也同意继续投入，但与此同时，德国的架构师提出了不同的意见，由于项目的其中一个长期计划需要将历史遗留的工作流引擎升级，而对旧系统的升级往往比较困难，因此他更期望我们先sunset老项目以减少项目后续的风险，但由于这个项目主要的下游业务方都用作业务编排，与我们的PoC相差甚远，因此我们需要重新评估工作内容和研究实现方案，这样势必会导致项目延期，但我的这个顾虑没能改变老板的意见，项目的上线目标还是临时进行了调整。
但事已至此我们只能接受，在调研完旧系统的几个下游业务方的业务复杂度之后，我们选定了一个复杂度最低的下游业务作为我们第一批次升级的目标，但由于业务方配合度不够，老板给我们重新找了一个愿意花时间配合我们升级系统的业务方，但坏消息是这个组的业务复杂度远高于前者，为此项目计划上线时间推迟了半年，更糟糕的是随着上海疫情反扑，长时间的wfh外加小组人员流动导致项目开发进度不理想，没有足够的场景测试，原定于22年下半年上线的目标再次被推迟。
而随着俄乌战争的发展，公司的业务持续受到影响，营收减少股价杀低，公司开始自上而下重新审计23年的项目计划，需要长期投入的项目除非特殊情况否则都需要暂停，于是磕磕绊绊了一年的项目最终还是倒在了上线前的最后一步。</p>

<h3 id="写在后面">写在后面</h3>
<p>经历过三次项目失败之后要说不失望是假的，但好在生活上也并不是一无所获，这大概也算是对冲了工作上的焦虑。又听闻就业市场一片惨淡，尚且能保住一份工作已是万幸，但愿坏的日子能早点过去而大家都能拥有好的未来。</p>

<p>Love and Peace.</p>]]></content><author><name>Leo</name><email>mail@nleo.me</email></author><category term="cn" /><summary type="html"><![CDATA[是很久没有写文章了，提笔的习惯一旦落下一时半会就很难再捡起来，仔细想想可能是因为三年前跳槽去某多多吧，工作忙起来确实没有精力再去整理自己的思路，虽说后面跑路回了外企却也是荒废掉了这个repo。最近工作上有不少感想，便想着在这里再写点东西，也不知道下一次断更会是什么时候，但愿不会太快。]]></summary></entry></feed>