<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <!-- Source: https://planetscale.com/blog/feed.atom -->
  <title>Blog — PlanetScale</title>
  <subtitle>Posts about the PlanetScale platform, MySQL, PostgreSQL, databases, and more.</subtitle>
  <link href="https://siftrss.com/f/y6MV6p117oA"/>
  <link rel="alternate" type="text/html" hreflang="en" href="https://planetscale.com/blog"/>
  <link rel="self" type="application/atom+xml" href="https://siftrss.com/f/y6MV6p117oA"/>
  <id>https://siftrss.com/f/y6MV6p117oA</id>
  <updated>2026-11-17T00:00:00.000Z</updated>
  <entry>
    <title>Introducing Insights Agent</title>
    <link href="https://planetscale.com/blog/introducing-insights-agent"/>
    <id>https://planetscale.com/blog/introducing-insights-agent</id>
    <published>2026-11-17T00:00:00.000Z</published>
    <updated>2026-11-17T00:00:00.000Z</updated>
    <author>
      <name>Elom Gomez</name>
    </author>
    <author>
      <name>Enrique Gonzalez</name>
    </author>
    <category term="product"/>
    <content type="html"><![CDATA[<p><a href="https://planetscale.com/docs/postgres/monitoring/query-insights">PlanetScale Insights</a> has long shown you exactly how your queries perform in production and recommended fixes using deterministic algorithms. However, fixing what it finds has been mostly up to <em>you</em> and <em>your</em> agents.</p><p>Today we&#x27;re introducing <strong>Insights Agent</strong>. These are agents built right into the PlanetScale platform that combine your code, database schema, and insights data in sandboxes that investigate and fix performance issues in your database and code. Better yet, you can set these up to trigger on a repeatable schedule, so you automatically get database speedup PRs into your repos.</p><p>We have run a ton of internal evaluations to tune these. We&#x27;ve carefully tested and chosen the right combinations of models, prompts, and sandbox environment to maximize the benefit of these agent runs.</p><blockquote><p>But I want to use <em>my</em> agent!</p></blockquote><p>Great! If you prefer to have a self-improving database powered by your own agent, the <a href="https://planetscale.com/docs/cli">PlanetScale CLI</a> and <a href="https://planetscale.com/docs/mcp-server">MCP server</a> have you covered. Combine these with your code, custom prompts, and agent-harness of choice and you can build a similar system on your own infrastructure or third-party providers. We even have a doc dedicated to helping you set up your own <a href="https://planetscale.com/docs/self-improving-database">self-improving database experience</a>.</p><p>Insights Agent has the advantage of (a) being super easy to get started with, and (b) comes tuned by us, allowing us to imbue our database expertise into the agents making your software better. Getting started is as simple as:</p><ol><li>Log in to the PlanetScale dashboard</li><li>Connect your GitHub or Cursor Origin repository</li></ol><p>…and let Insights Agent cook. Let&#x27;s look at what it does and how it works.</p><h2 id="suggestions-while-you-sleep"><a href="https://planetscale.com/blog/introducing-insights-agent#suggestions-while-you-sleep">Suggestions while you sleep</a></h2><p>At launch, Insights Agent can perform two different types of &quot;run.&quot; Each run has a deliberately narrow focus with an instruction to create improvements to your database performance, though that might mean more than one file, query or schema change is proposed. You can initiate runs on-demand (via the app, MCP, or CLI) or on a schedule.</p><p>Within each run you&#x27;ll see a timeline of its investigation and decisions made along the way.</p><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/agent-runs-DydKZHdB.png?auto=compress%2Cformat"><source media="(prefers-color-scheme: dark)" srcSet="https://planetscale-images.imgix.net/assets/agent-runs-darkmode-Otuz1-mw.png?auto=compress%2Cformat"><img alt="Insights Agent runs" src="https://planetscale-images.imgix.net/assets/agent-runs-DydKZHdB.png?auto=compress%2Cformat" width="2992" height="1548" loading="lazy"></picture></p><h3 id="schema-recommendation-runs"><a href="https://planetscale.com/blog/introducing-insights-agent#schema-recommendation-runs">Schema recommendation runs</a></h3><p>These inspect the schema of your database and gather evidence from Query Insights such as rows read against rows returned, index usage patterns, and query run stats. From its sandbox, it compares that against your code and if the evidence supports a change, it opens a pull request. If not, the run finishes with a short explanation and is closed.</p><p>The agent will use conventions established in your code for its suggested changes. For example a pull request may be opened with updates as appropriate for Drizzle, Laravel, Go, or even raw SQL queries. On Vitess, a <a href="https://planetscale.com/docs/vitess/schema-changes/deploy-requests">deploy request</a> will also be opened.</p><h3 id="slow-query-runs"><a href="https://planetscale.com/blog/introducing-insights-agent#slow-query-runs">Slow query runs</a></h3><p>These look through Insights data for slow queries and follow the same path to look for code changes which should speed up slow queries. The agent evaluates possible changes within its sandbox and will either close the suggestion or create a pull request.</p><p>In either type of run, if you choose not to proceed with the pull request, the run is closed and on Vitess the deploy request is closed also.</p><p>Neither run will automatically merge or deploy any changes. Pull requests are opened as suggestions and are left up to you (or your agent) to review and either merge or close.</p><h2 id="fixes-on-demand"><a href="https://planetscale.com/blog/introducing-insights-agent#fixes-on-demand">Fixes on-demand</a></h2><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/fix-with-agent-DLUhnyL9.png?auto=compress%2Cformat"><source media="(prefers-color-scheme: dark)" srcSet="https://planetscale-images.imgix.net/assets/fix-with-agent-darkmode-C65xi5_I.png?auto=compress%2Cformat"><img alt="Fix with agent on a recommendation" src="https://planetscale-images.imgix.net/assets/fix-with-agent-DLUhnyL9.png?auto=compress%2Cformat" width="2992" height="1548" loading="lazy"></picture></p><p>Insights already contains recommendations and slow query pages (and has for a long time). These now have a &quot;Fix with agent&quot; button to perform a run against that specific issue on demand.</p><h2 id="costs-and-privacy"><a href="https://planetscale.com/blog/introducing-insights-agent#costs-and-privacy">Costs and privacy</a></h2><p>Runs are only charged if they work to completion. Costs are accumulated per-run, added to your monthly bill, and based on the tokens required to perform the investigation and create the pull request.</p><p>Spend limits can be configured by organization administrators to set a maximum spend on runs.</p><p>Insights Agent uses models from OpenAI and Anthropic with zero data retention. The sandbox environment used to perform runs only exists for the duration of the run. On Vitess, opening a deploy request can also create a development branch, and the associated branch is billed as normal.</p><p>Insights Agent is on by default, and takes no action until a repository is connected to a database. An organization administrator can turn it off from your organization page under Settings → Overview → Insights Agent.</p><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/ai-features-UU-56HU7.png?auto=compress%2Cformat"><source media="(prefers-color-scheme: dark)" srcSet="https://planetscale-images.imgix.net/assets/ai-features-darkmode-CwLNeWLR.png?auto=compress%2Cformat"><img alt="Organization AI features, with LLM usage and Insights Agent enabled" src="https://planetscale-images.imgix.net/assets/ai-features-UU-56HU7.png?auto=compress%2Cformat" width="2112" height="1101" loading="lazy"></picture></p><p>Administrators are responsible for the integration between each database and a repository. At launch, only one GitHub or Cursor Origin repository can be connected to a database, but the same repository can be connected to multiple databases.</p><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/repository-integrations-DNJPM86o.png?auto=compress%2Cformat"><source media="(prefers-color-scheme: dark)" srcSet="https://planetscale-images.imgix.net/assets/repository-integrations-darkmode-BaYunsug.png?auto=compress%2Cformat"><img alt="Connect a Cursor Origin or GitHub repository" src="https://planetscale-images.imgix.net/assets/repository-integrations-DNJPM86o.png?auto=compress%2Cformat" width="2992" height="1548" loading="lazy"></picture></p><h2 id="is-mcp-cli-or-insights-agent-for-me"><a href="https://planetscale.com/blog/introducing-insights-agent#is-mcp-cli-or-insights-agent-for-me">Is MCP, CLI or Insights Agent for me?</a></h2><p>You may be asking, should I use <strong>Insights Agent</strong>, use my own agent, or both?</p><p>With a combination of scheduled cloud agents (eg: <a href="https://cursor.com/docs/cloud-agent/automations">Cursor automations</a>), the PlanetScale MCP Server and CLI, and proper access to your git repositories, you can <a href="https://planetscale.com/docs/self-improving-database">string together</a> a similar experience yourself.</p><p>Our MCP server and CLI can both be authenticated by a service token for use in automation / CI environments, and can fetch data from Query Insights. In this case, you&#x27;re in charge of writing prompts for the sorts of improvements you&#x27;d like to see, or problems you&#x27;re looking to solve, as well as setting up an automation schedule or on-demand trigger.</p><p>Building these processes yourself gives you more control. You may have specific quirks or requirements in your codebase, and you want to give these automations custom prompts, skills, and other context from your organization. It also may be preferable if you want to use your committed token spend or subscription usage.</p><p>In contrast, the <strong>Insights Agent</strong> works inside of PlanetScale&#x27;s authentication, is tied to your application&#x27;s code via a connection to your repository, and is given curated and targeted prompts when performing the two types of &quot;runs&quot; which are currently available. We manage all the moving parts: the inference, sandboxing, and creation of resulting reports and pull requests. <strong>Insights Agent</strong> is the perfect out-of-the-box solution for getting improvements into your database schema and code with minimal setup on your end.</p><h2 id="availability"><a href="https://planetscale.com/blog/introducing-insights-agent#availability">Availability</a></h2><p>Insights Agent is available today on all plans, for all engines (Vitess, Neki, and Postgres) on all hosts.</p><p>Connect your repository to get started. See the <a href="https://planetscale.com/docs/insights-agent">Insights Agent documentation</a> for setup, scheduling, and billing details.</p>]]></content>
    <summary><![CDATA[Insights Agent connect to your codebase to turn slow queries and schema recommendations into pull requests.]]></summary>
  </entry>
  <entry>
    <title>Designing a reliable unplanned failover</title>
    <link href="https://planetscale.com/blog/designing-a-reliable-unplanned-failover"/>
    <id>https://planetscale.com/blog/designing-a-reliable-unplanned-failover</id>
    <published>2026-11-05T00:00:00.000Z</published>
    <updated>2026-11-05T00:00:00.000Z</updated>
    <author>
      <name>Shlomi Noach</name>
    </author>
    <category term="engineering"/>
    <category term="neki"/>
    <content type="html"><![CDATA[<p>In <a href="https://planetscale.com/blog/designing-a-planned-switchover-for-minimum-disruption">Designing a planned switchover for minimum disruption</a>, we discussed how Neki moves Postgres primaryship when all the participants are healthy. Admin, Neki&#x27;s control plane, knows when the primary is going to step aside. It can inspect the shard, select a target, and prepare the handoff before causing any disruption. This is the &quot;planned&quot; in &quot;planned switchover.&quot;</p><p>An unplanned failover begins with none of those advantages. This happens in circumstances with unexpected (though still well-handled) failure modes, like a network link being cut or server hardware failure.</p><p>Neki&#x27;s Admin system does not know whether the primary has failed or is merely unreachable from where Admin happens to run. It has no promotion target selected, and it cannot ask the primary for a final WAL position. Meanwhile, applications cannot reliably write.</p><p>There are two questions to answer in this scenario:</p><ol><li>Is the primary effectively unavailable?</li><li>Which replica can safely take over?</li></ol><h2 id="when-is-a-primary-dead"><a href="https://planetscale.com/blog/designing-a-reliable-unplanned-failover#when-is-a-primary-dead">When is a primary dead?</a></h2><p>A Neki shard consists of one Postgres primary and multiple replicas. The primary accepts writes, and each replica continuously receives and replays the primary&#x27;s WAL. If the primary fails, one of those replicas needs to take over.</p><p>Suppose our shard has a primary <code>P</code> and replicas <code>R1</code>, <code>R2</code>, and <code>R3</code>. Admin runs a health check against <code>P</code> and gets... no response!</p><p>You might be asking if Admin should promote a replica. The answer is not yet. <code>P</code> may have crashed or its network may be isolated. Or the failure may be only between Admin and <code>P</code>, while applications and replicas are all still communicating normally.</p><p>A common way to gain confidence is for Admin to repeat the health check with the primary several times. If the primary does not answer after some number of attempts, you can declare it dead. Repetition helps with transient packet loss, but if Admin is on the isolated side of a network partition, this won&#x27;t help so long as the partition exists.</p><p>Other high-availability systems use a lease. An agent on the primary holds a regularly-renewed key in a distributed store. If the key expires, the primary is considered failed. This is a well-established design. While Neki also has a distributed topology service, it does not use leases for primary health determination.</p><p>Neki, instead, asks the replicas.</p><p>Each replica reports its view of physical replication, taken from <code>pg_stat_wal_receiver</code>. We can now distinguish between a few cases:</p><ul><li>If Admin cannot reach <code>P</code>, but a replica is still streaming from it, the evidence does not justify failover.</li><li>If Admin cannot reach <code>P</code>, at least one reachable replica reports broken replication, and no reachable replica contradicts it, Neki can classify <code>P</code> as dead and attempt recovery.</li><li>If Admin cannot reach <code>P</code> or any replica, Neki does not fail over. It has neither corroborating evidence nor a visible candidate to promote.</li></ul><p>In the last case, Admin waits. Promoting from its failed health check alone would risk creating a second writable primary.</p><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/detection-points-of-view-CRpnYU8T.svg?auto=compress%2Cformat"><source media="(prefers-color-scheme: dark)" srcSet="https://planetscale-images.imgix.net/assets/detection-points-of-view-darkmode-BTn05UHz.svg?auto=compress%2Cformat"><img alt="An animation of three cases for one shard. Primary P and replicas R1, R2, and R3 sit inside the shard, and Admin sits outside it. Blue replication links run from P to each replica, and purple health checks run from Admin to P and to each replica. In case 1, Admin can&#x27;t reach P, but the replicas still stream from it, so Neki does not promote. In case 2, Admin can&#x27;t reach P and every replica&#x27;s replication from P is broken, while Admin still reaches the replicas. The replicas report the break, so Neki begins recovery. In case 3, Admin can&#x27;t reach P or any replica, so it sees nothing inside the shard and waits." src="https://planetscale-images.imgix.net/assets/detection-points-of-view-CRpnYU8T.svg?auto=compress%2Cformat" width="1504" height="790" loading="lazy"></picture></p><h2 id="why-the-replicas-view-matters"><a href="https://planetscale.com/blog/designing-a-reliable-unplanned-failover#why-the-replicas-view-matters">Why the replicas&#x27; view matters</a></h2><p>Neki&#x27;s default synchronous durability policy configures Postgres with:</p><div class="code-block" data-language="text"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span>synchronous_standby_names = 'ANY 1 (R1, R2, R3)'</span></span>
<span class="line"><span></span></span></code></pre></div></div><p>With <code>synchronous_commit = on</code>, <code>P</code> does not acknowledge a commit until at least one eligible replica has durably flushed its WAL. The acknowledging replica can vary from one commit to the next. <code>R1</code> may acknowledge a commit at time <code>T</code> and <code>R3</code> the next one, at <code>T+1</code>.</p><p>Now consider the case that triggers a failover: Admin cannot reach <code>P</code>, and neither can any replica. <code>P</code> may have crashed, or it may still be running and is simply unreachable from Admin nodes. Either way, <code>P</code> cannot complete a synchronous commit, because no replica can ack. Writes are effectively blocked even if <code>P</code> is still alive. Promoting a replica replaces the now-unwritable primary.</p><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/any-one-acknowledgements-COj13bxO.svg?auto=compress%2Cformat"><source media="(prefers-color-scheme: dark)" srcSet="https://planetscale-images.imgix.net/assets/any-one-acknowledgements-darkmode-Cx75FjKd.svg?auto=compress%2Cformat"><img alt="An animation of primary P and replicas R1, R2, and R3 under ANY 1 synchronous replication, in five steps. Each commit P writes waits for one replica to flush it. R1 acknowledges the first two commits. R3 overtakes R1 and acknowledges the third. R2 lags behind and holds none of the acknowledged commits. Then P loses every replica: replication breaks, and the replicas stop at different positions. The next commits P writes wait with no replica left to acknowledge them, so commits are blocked." src="https://planetscale-images.imgix.net/assets/any-one-acknowledgements-COj13bxO.svg?auto=compress%2Cformat" width="1504" height="664" loading="lazy"></picture></p><p>When some replicas are also unreachable, their view is unknown: one (say <code>R1</code>) might still be connected to <code>P</code>. We are thus unable to determine that <code>P</code> is not taking writes.</p><p>The two could be functioning correctly together, but in isolation from Admin and the other replicas. This all counts as within the bounds of the <code>ANY 1</code> contract. A way to mitigate this issue is to configure Neki to only accept replication acknowledgements from cross-availability-zone replicas, reducing the possibility of the two being network isolated together.</p><p>Neki still fails over under such conditions, as long as at least one reachable replica reports broken replication and none contradict it.</p><p>Neki also supports asynchronous durability. With async, <code>P</code> does not wait for replicas to acknowledge writes, so we cannot deduce that it stopped accepting writes. An unreachable primary with every replica disconnected is a very strong signal, but not a guarantee.</p><h2 id="detecting-failure"><a href="https://planetscale.com/blog/designing-a-reliable-unplanned-failover#detecting-failure">Detecting failure</a></h2><p>Detection logic and speed vary by failure type. Let&#x27;s consider some common scenarios.</p><p>Say the Postgres process crashes and exits with an error for whatever reason. Neki runs Postgres via PostgresManager, a component that starts, stops, configures, and otherwise controls the Postgres process. A goroutine waits on the Postgres process, and when the process exits on primary <code>P</code>, PostgresManager knows immediately. It sends a <code>PROCESS_EXITED</code> event to Admin, which marks <code>P</code> as unreachable and begins a burst of shard analysis to cross-validate with <code>P</code>&#x27;s replicas. The detection is still incomplete, waiting for confirmation from the replicas.</p><p>Another common scenario is rejected connections. Perhaps a firewall now stands between <code>P</code> and the rest of the shard, and actively rejects its traffic. This is straightforward: Admin&#x27;s health checks and the replicas&#x27; replication connections fail right away with an error.</p><p>Dropped packets are harder. If <code>P</code>&#x27;s host is down, or the network silently discards its traffic, nobody gets an error. A connection can look established long after there is anything on the other side.</p><p>And a frozen Postgres process is perhaps the hardest of all. The server&#x27;s kernel keeps answering at the TCP level, so the connection looks healthy even though Postgres is doing no work.</p><p>How does a replica tell these cases apart? It doesn&#x27;t need to. Neki tunes the Postgres replication settings so that each of them, and the many combinations we did not list, ends the same way: the replica reports broken replication.</p><ul><li>Short TCP keepalive settings and <code>tcp_user_timeout</code> on the replication connection catch dropped packets.</li><li><code>wal_receiver_timeout</code> catches the frozen process, which TCP alone cannot. If <code>P</code> sends nothing for a few seconds, the replica closes the connection and reports replication as broken.</li></ul><h2 id="committing-to-a-failover"><a href="https://planetscale.com/blog/designing-a-reliable-unplanned-failover#committing-to-a-failover">Committing to a failover</a></h2><p>Once Neki considers <code>P</code> dead, the shard needs a new primary. We must pick a suitable candidate replica, and proceed to promote it while reconfiguring the rest of the replicas to accept it as their new primary. We have two problems, though:</p><ol><li><code>P</code> may return to being &quot;alive&quot; at any moment.</li><li>The replicas may have received different amounts of WAL before replication broke.</li></ol><h2 id="disconnecting-the-replicas"><a href="https://planetscale.com/blog/designing-a-reliable-unplanned-failover#disconnecting-the-replicas">Disconnecting the replicas</a></h2><p>Why would we need to disconnect replicas whose replication is already broken? Because <code>P</code> may return. If it returns before Admin decides to fail over, there is no harm. The replicas just reconnect, and after a short blip the shard is healthy. The problem is if <code>P</code> returns after Admin has decided to fail over. By then, Admin is converging the shard on a new primary, but a broken connection can still reconnect. WAL positions would begin moving again, and <code>P</code> would once again have replicas that can acknowledge its commits.</p><p>There is a MySQL command that allows an administrator to stop receiving changes from the primary, without stopping replication altogether: <code>STOP REPLICA IO_THREAD</code>. Postgres does not offer an equivalent command for physical replication. Instead, Neki makes a small, reversible change to each reachable replica&#x27;s <code>primary_conninfo</code>: it prefixes the hostname of <code>P</code> with <code>//</code>. The replica can no longer find <code>P</code>, and so it cannot reconnect.</p><p>This is the same mechanism the <a href="https://planetscale.com/blog/designing-a-planned-switchover-for-minimum-disruption">planned switchover</a> uses to freeze replica WAL positions before the handoff.</p><p>Disconnecting the replicas serves two purposes.</p><p>First, it protects the shard from <code>P</code> becoming healthy unexpectedly. If <code>P</code> comes back, the disconnected replicas will not reconnect to it. With <code>ANY 1</code>, <code>P</code> cannot complete a commit without a replica to acknowledge it, so it will not be able to accept any writes.</p><p>Second, it freezes the replicas&#x27; WAL positions. Once no replica can receive more WAL from <code>P</code>, each one&#x27;s reported position is final. The positions are a stable account of the current view of the WAL, which is what we&#x27;ll use to choose a new primary.</p><h2 id="choosing-from-the-wal-position"><a href="https://planetscale.com/blog/designing-a-reliable-unplanned-failover#choosing-from-the-wal-position">Choosing from the WAL position</a></h2><p>In a planned switchover, Admin picks the new primary in advance, while the old primary is still healthy. An unplanned failover has no such luxury, so we must choose from the WAL that survived.</p><p>Suppose the replicas stop at these positions:</p><div class="code-block" data-language="text"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span>R1  receive: 120  replay: 120</span></span>
<span class="line"><span>R2  receive: 125  replay: 122</span></span>
<span class="line"><span>R3  receive: 123  replay: 123</span></span>
<span class="line"><span></span></span></code></pre></div></div><p>The highest received position is 125, on <code>R2</code>. Admin first looks for a promotable replica that has already replayed through 125. There is none in this snapshot, so it waits briefly and checks again. If <code>R2</code> replays its locally stored WAL through 125, it becomes a candidate.</p><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/choosing-a-candidate-DgTvCgOM.svg?auto=compress%2Cformat"><source media="(prefers-color-scheme: dark)" srcSet="https://planetscale-images.imgix.net/assets/choosing-a-candidate-darkmode-Cl-dZYFB.svg?auto=compress%2Cformat"><img alt="An animation of received and replayed WAL positions for R1, R2, and R3 in five steps. P fails, and the replicas stop receiving WAL at 120, 125, and 123. Admin discards P and disconnects the replicas. The highest received position, 125, is on R2. R2 keeps replaying the WAL it already received, and once it has replayed through 125, Admin chooses it for promotion." src="https://planetscale-images.imgix.net/assets/choosing-a-candidate-DgTvCgOM.svg?auto=compress%2Cformat" width="1504" height="560" loading="lazy"></picture></p><p>If no replica catches up within that window, Admin chooses the promotable replica with the highest <code>receive_lsn</code>, using <code>replay_lsn</code> as the next criterion.</p><p>Admin can take the maximum across replicas because WAL is sequential: a replica that received position 125 also received the WAL before it. Neki does not need to know whether <code>R1</code>, <code>R2</code>, or <code>R3</code> acknowledged each individual commit. It needs a surviving candidate whose WAL covers the acknowledged history.</p><p>The latest WAL may also be on a replica we cannot promote. <code>ANY 1</code> promises that each acknowledged commit arrived at <em>some</em> replica, not that the replica still exists. If <code>P</code> and that replica fail together, the commit is lost. Requiring cross-availability-zone acknowledgements makes that much less likely, at the cost of commit latency.</p><h2 id="what-happens-at-promotion"><a href="https://planetscale.com/blog/designing-a-reliable-unplanned-failover#what-happens-at-promotion">What happens at promotion?</a></h2><p>Admin creates replication slots on the new primary for the other replicas and promotes it in Postgres. It then marks it as the shard&#x27;s primary, and Neki&#x27;s Routers start sending writes its way. Last, Admin repoints the other replicas to the new primary.</p><p>Choosing the highest received position pays off a second time here. All other replicas hold a prefix of the new primary&#x27;s WAL, so they can simply follow it onto the new timeline. The exception is a replica that was ahead of the candidate but could not be promoted, for example while under maintenance. Neki must rewind or rebuild it before it can follow.</p><p>Writes do not resume quite yet. The new primary runs with <code>ANY 1</code>, so its first commits wait until a replica attaches and acknowledges them.</p><h2 id="what-about-p"><a href="https://planetscale.com/blog/designing-a-reliable-unplanned-failover#what-about-p">What about <code>P</code>?</a></h2><p>Admin marks <code>P</code> as <code>TEARDOWN</code>. A <code>TEARDOWN</code> node serves no traffic, takes no part in replication, and Admin stops monitoring it. As far as the shard is concerned, <code>P</code> is gone, even if it comes back to life.</p><p>After a planned switchover, Admin turns <code>P</code> into a replica of the new primary. After an unplanned failover, we do not. <code>P</code> may have writes that don&#x27;t exist on the new primary, and we prefer not to trust it just because it became reachable again.</p><p>That does not mean we must get rid of it right away. A failed primary is often the best evidence of what went wrong: its logs, its last WAL, the state of its disk. We may want to keep it around for a postmortem. Only then do we destroy it, recycle it, or, by explicit decision, rejoin it to the shard as a replica.</p><h2 id="summary"><a href="https://planetscale.com/blog/designing-a-reliable-unplanned-failover#summary">Summary</a></h2><p>An unplanned failover starts with uncertainty: Admin does not know whether <code>P</code> is dead, or only out of its sight. Neki does not act on Admin&#x27;s view alone. It asks the replicas, and fails over only when those it can reach agree that <code>P</code> is gone.</p><p>From there, we assume the worst about <code>P</code>: it may come back at any moment. Disconnecting the replicas keeps a returning <code>P</code> from regaining them, and freezes their WAL. Choosing the highest WAL position for the replacement keeps every acknowledged commit that a promotable replica holds, and lets the other replicas follow easily.</p><p>Some outages are beyond automatic recovery. Admin cannot promote a replica it cannot contact, nor recover WAL that disappeared with every machine that held it.</p><p>Admin itself can fail, too, but that is a topic for a future post.</p>]]></content>
    <summary><![CDATA[How Neki detects a failed Postgres primary, and chooses a new one from the WAL that survived.]]></summary>
  </entry>
  <entry>
    <title>The hidden latency inside your database</title>
    <link href="https://planetscale.com/blog/the-hidden-latency-inside-your-database"/>
    <id>https://planetscale.com/blog/the-hidden-latency-inside-your-database</id>
    <published>2026-11-03T00:00:00.000Z</published>
    <updated>2026-11-03T00:00:00.000Z</updated>
    <author>
      <name>Simeon Griggs</name>
    </author>
    <category term="engineering"/>
    <content type="html"><![CDATA[<p>Network-attached storage is a fine choice and a bad default.</p><p>Application performance 101 says you want to move your application as close as possible to your database. The shorter that distance across the network, the faster reads and writes move between them.</p><iframe src="https://planetscale.com/blog/the-hidden-latency-inside-your-database/iframe#app-to-database" title="An app in us-west-1 exchanges packets with a database in us-east-1, then moves next to the database so both share one host" loading="lazy"></iframe><p>But did you know there is network latency <em>inside</em> your database cluster?</p><p>Most commonly, cloud-hosted databases have <strong>network-attached</strong> storage: a disk on a separate server, connected over the network, with impressively small, but still measurable, latency.</p><p>Alternatively, it&#x27;s possible to have <strong>locally attached</strong> storage: a disk inside the same machine as the CPU, connected directly to the motherboard.</p><p>Network-attached storage powers an extraordinarily high volume of data throughput with flexibility and durability. But local disks are closer, closer is faster, and faster is better.</p><h2 id="howd-we-get-here"><a href="https://planetscale.com/blog/the-hidden-latency-inside-your-database#howd-we-get-here">How&#x27;d we get here</a></h2><p>The work performed by the device you&#x27;re reading this blog post on has two separate yet equally important components: a processor to perform work, and storage to save it. <em>Dun dun</em>.</p><p>It&#x27;s also extremely likely these two are contained in one piece of hardware, like a smartphone or laptop. Computers have been like this forever.</p><p>Internet infrastructure started this way, too. The original database servers, like Sun&#x27;s SPARC servers, had their own disks inside the chassis or in a cabinet next to it, connected by SCSI and later SAS cables. Storage and compute were in the same physical hardware.</p><h3 id="separating-compute-and-storage"><a href="https://planetscale.com/blog/the-hidden-latency-inside-your-database#separating-compute-and-storage">Separating compute and storage</a></h3><p>But a single entity for storage is not <em>durable</em>. RAID (Redundant Array of Inexpensive Disks) was popularized in the late 1980s. With multiple storage disks being kept in sync, should one die, it could be swapped out for another. The system relied on the still-active disks while the fresh one caught up.</p><p>Into the 1990s and early 2000s, enterprises put storage in dedicated arrays. A SAN (Storage Area Network) connected storage to compute over a network. But these were tremendously expensive and often maintained by the enterprise itself.</p><h3 id="the-cloud"><a href="https://planetscale.com/blog/the-hidden-latency-inside-your-database#the-cloud">The cloud</a></h3><p>a.k.a. <em>renting someone else&#x27;s computer</em>.</p><p>(For simplicity, we&#x27;re focusing on AWS offerings in this post, but PlanetScale also runs on Google Cloud Platform and Azure.)</p><p>The most notable cloud storage service is AWS S3 (Simple Storage Service). It is a key-value store for objects. You can&#x27;t attach it as a block device or modify subsets of objects in place.</p><p>Enter AWS EBS (Elastic Block Store), which mounts like a disk and can be provisioned on demand. EBS solves for typical storage use cases like that of a database at a lower cost than the previous generations&#x27; enterprise SANs.</p><p>Dedicated storage like EBS is durable, in that data is replicated across multiple disks within the same availability zone. Losing any one disk within that availability zone won&#x27;t lead to data loss.</p><p>Note that for this reason PlanetScale replicates data <em>across</em> availability zones, as the failure of a single zone would be a data unavailability or loss event.</p><p>It&#x27;s also flexible: you aren&#x27;t constrained to a single volume&#x27;s storage size as adding capacity is as simple as resizing the same volume.</p><h3 id="disks-got-fast"><a href="https://planetscale.com/blog/the-hidden-latency-inside-your-database#disks-got-fast">Disks got fast</a></h3><p>At launch in 2008, EBS used spinning disks like the enterprise servers of the past. And so throughout the history of network-attached storage, the speed of the spinning disk was often of more significance than the speed of data transfer over the network. The average random read on an HDD is 10-20ms, whereas a network round trip in the same data-center is usually 1 millisecond or less.</p><p>In 2012, EBS began swapping out spinning disks for SSDs. Disk operations got ~100x faster and suddenly network latency was the biggest bottleneck to performance.</p><p>Initially the swap to SSDs didn&#x27;t yield the sort of free speed increase you might expect.</p><blockquote><p>... it certainly did address the problems that came from the mechanics of hard drives. But what surprised us was that the system didn&#x27;t improve nearly as much as we had hoped ...</p></blockquote><p>— <a href="https://www.allthingsdistributed.com/2024/08/continuous-reinvention-a-brief-history-of-block-storage-at-aws.html">Continuous reinvention: A brief history of block storage at AWS</a>, Marc Olson, All Things Distributed</p><p>To address this, engineers at AWS created new custom hardware and a unique network transfer protocol (SRD). Network latency improved.</p><p>So, over the brief history of data centers, storage and compute got separated when storage was slower than the network and were then penalized for that once the opposite was true.</p><p>You can continue to try and solve problems, or you can eliminate them.</p><h2 id="hops-hiding-in-plain-sight"><a href="https://planetscale.com/blog/the-hidden-latency-inside-your-database#hops-hiding-in-plain-sight">Hops hiding in plain sight</a></h2><p>Back to our original Performance 101 lesson. Moving your application closer to your database makes as much sense as moving your database&#x27;s compute closer to its storage.</p><p>Network latency is a long-established expectation of working with remote servers and cloud storage, but it doesn&#x27;t have to be.</p><iframe src="https://planetscale.com/blog/the-hidden-latency-inside-your-database/iframe#ec2-to-ebs" title="The app in us-east-1 sends packets to the database, which opens up to reveal EC2 compute exchanging network packets with EBS network storage inside it" loading="lazy"></iframe><p>In a typical cloud-hosted database scenario, you buy an EC2 instance for compute to perform work and attach it to an EBS volume for storage.</p><p>The EBS volume shows up in the operating system as if it were an attached storage device. On current-generation instances, a dedicated Nitro card turns every read and write into a network request.</p><p>For every non-Metal PlanetScale database, this is what you have and it works just fine.</p><p>However, some EC2 instance types also come with local NVMe disks, physically attached to the host server. These aren&#x27;t EBS volumes. As they&#x27;re locally attached, there&#x27;s no network hop for reads and writes.</p><p>If all you wanted was speed, it <em>just makes sense</em> to put your database and its storage on a self-contained instance.</p><iframe src="https://planetscale.com/blog/the-hidden-latency-inside-your-database/iframe#cpu-to-local-storage" title="Zooming into EC2 reveals its CPU wired directly to local storage, with packets moving between them almost instantly" loading="lazy"></iframe><p>But if this is so obvious, why is it so rarely offered? Because without careful management the risk is too high. Locally attached storage lives and dies with compute. Its size is rigid and its data is not automatically replicated.</p><p>It&#x27;s no good being fast if you&#x27;re not also flexible, reliable, and durable. That&#x27;s what we solved with PlanetScale Metal.</p><h2 id="durable-local-disks"><a href="https://planetscale.com/blog/the-hidden-latency-inside-your-database#durable-local-disks">Durable local disks</a></h2><p>So, for a faster database you want to eliminate the network hop between storage and compute. But you can&#x27;t afford to lose data, so storage still has to be durable.</p><p>Get you somebody who can do both.</p><p>Firstly, every Metal database cluster has a primary and at least two replicas. Each runs on its own VM with its own local NVMe drive, spread across distinct availability zones.</p><iframe src="https://planetscale.com/blog/the-hidden-latency-inside-your-database/iframe#zone-durability" title="PlanetScale Metal runs an instance with local storage in each availability zone, so when one zone fails the others keep serving" loading="lazy"></iframe><p>Each replica is treated as a potential primary that can be failed over to. To ensure the integrity and suitability of these replicas and the durability of this storage, commits must be acknowledged on at least one replica before the primary sends acknowledgement to the client.</p><p>You might ask, doesn&#x27;t this introduce a network hop into every commit? Yes, but it happens only once per commit. A Metal database confirming a write landed in a replica in another availability zone ensures durability. EBS-backed databases require network hops for every disk operation, including something as simple as a cache miss in a read query. It&#x27;s also likely the majority of your queries are reads, and reads on Metal will never cross the network.</p><p>With each replica treated like a primary in waiting, should the primary fail, a replica is immediately promoted. On Vitess, queries are buffered during the switch. On Postgres, queries through PgBouncer are buffered and then directed to the new primary.</p><p>PlanetScale Metal is a mature alternative to network-attached storage and has already powered trillions of queries across petabytes of data.</p><h2 id="network-vs-local-vs-your-budget"><a href="https://planetscale.com/blog/the-hidden-latency-inside-your-database#network-vs-local-vs-your-budget">Network vs local vs your budget</a></h2><p>Incredibly, we haven&#x27;t yet touched on IOPS (Input/Output Operations Per Second). That is, the throughput limits of your database. On EBS your IOPS are limited, defaulting to 3,000. This makes sense: the transfer of data across the network between the two services has to be curbed to some number or else one noisy neighbor risks flooding the network.</p><p>But with locally attached disks this isn&#x27;t a problem. Unlike network-attached, there&#x27;s no artificial cap on IOPS.</p><p>In our <a href="https://planetscale.com/blog/benchmarking-postgres-17-vs-18">Postgres 17 vs 18 benchmarks</a>, an <code>r7i</code> with a 700 GB <code>io2</code> volume provisioned for 16,000 IOPS cost $1,513.82 a month on demand. An <code>i7i</code> with a 1.8 TB local NVMe drive, capable of around 300,000 IOPS, cost $551.15.</p><p>At launch, PlanetScale Metal only offered large compute and storage sizes. But with the launch of $50 Metal in December 2025, you can provision virtual machines as small as 1/8 vCPU with 1 GB of memory and 10 GB NVMe storage. vCPU and memory sizes go up from there, but storage can be individually configured in different sizes.</p><p>So while I spent much of this article telling you how inflexible local disks can be, we&#x27;ve done the hard work to make using them easy and reliable.</p><h2 id="you-might-not-need-metal"><a href="https://planetscale.com/blog/the-hidden-latency-inside-your-database#you-might-not-need-metal">You might not need Metal</a></h2><p>More incredible than the late mention of IOPS in this article is finally getting around to RAM. Volatile storage that also lives and dies with compute, but which can hold the most frequently and recently requested data as a cache.</p><p>Our own documentation for PlanetScale Metal mentions that you simply might not need Metal if the majority of your read workloads fit in RAM and you have a low volume of writes. Reads stay fast because they&#x27;re read from memory, not storage, and so never make that annoyingly slow network hop to EBS.</p><p>And so truthfully, depending on your workload, network-attached storage might be just fine, and you can use both on PlanetScale.</p><h2 id="signs-you-absolutely-need-metal"><a href="https://planetscale.com/blog/the-hidden-latency-inside-your-database#signs-you-absolutely-need-metal">Signs you absolutely need Metal</a></h2><p>If your most frequently requested data is too large or changes too often to fit in RAM, as in frequent cache misses, you want to eliminate those network-storage round-trips. Retrieving data from locally attached storage is closer to RAM speeds than a network round-trip.</p><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/insights-block-cache-hit-ratio-DOh91B5q.png?auto=compress%2Cformat"><source media="(prefers-color-scheme: dark)" srcSet="https://planetscale-images.imgix.net/assets/insights-block-cache-hit-ratio-darkmode-BJ0hgGrO.png?auto=compress%2Cformat"><img alt="PlanetScale Insights listing queries sorted by block cache hit ratio, alongside their count, total time, and CPU time." src="https://planetscale-images.imgix.net/assets/insights-block-cache-hit-ratio-DOh91B5q.png?auto=compress%2Cformat" width="2646" height="1490" loading="lazy"></picture></p><p><em>PlanetScale Insights can reveal the cache hit ratio of your queries. Also available to your agents via the MCP server.</em></p><p>Or if you&#x27;re hitting those expensive IOPS limits on EBS, it&#x27;s likely your workload will not only be faster on Metal, but cheaper, too.</p><p>Or if your CPU usage is low but latency is high, you&#x27;re being throttled by disk reads and paying for compute you can&#x27;t use. In <a href="https://planetscale.com/docs/metal/metal-performance">some cases</a> we&#x27;ve seen CPU usage go from 20-25% to 80% or more after moving to Metal.</p><p>Whether you want network-attached or locally attached storage, you can get either from PlanetScale. But if you&#x27;ve not considered the benefits of locally attached storage before, there&#x27;s never been a better time to <a href="https://planetscale.com/contact">get in touch</a>.</p>]]></content>
    <summary><![CDATA[Network-attached storage is a fine choice and a bad default.]]></summary>
  </entry>
  <entry>
    <title>What was the turning point for Postgres?</title>
    <link href="https://planetscale.com/blog/what-was-the-turning-point-for-postgres"/>
    <id>https://planetscale.com/blog/what-was-the-turning-point-for-postgres</id>
    <published>2026-10-27T00:00:00.000Z</published>
    <updated>2026-10-27T00:00:00.000Z</updated>
    <author>
      <name>Simeon Griggs</name>
    </author>
    <category term="engineering"/>
    <category term="postgres"/>
    <content type="html"><![CDATA[<p>Postgres is the most popular database choice among developers. Postgres is the default choice for agents, powering countless applications where those new to app building don&#x27;t even know what a database is. Every major cloud offers hosted Postgres.</p><p>But in a time where software development is being turned on its head, and new tooling unlocks an age of ambition never before seen, was there a pivotal moment that led to a database technology from the 80s becoming the default choice it is today?</p><h2 id="clarifying-default-choice"><a href="https://planetscale.com/blog/what-was-the-turning-point-for-postgres#clarifying-default-choice">Clarifying &quot;default choice&quot;</a></h2><p>I can already hear your objections, mostly because I&#x27;ve heard them from my colleagues here at PlanetScale. Of course we still love and maintain massive MySQL workloads running on Vitess. MySQL&#x27;s not dead. WordPress and its massive install base of MySQL databases haven&#x27;t gone away. Meanwhile, Oracle might edge out MySQL and Postgres in revenue.</p><p>However, current data suggests Postgres is the default choice for most new applications. Whether builders choose it knowingly or their agents choose it for them.</p><p>Several <a href="https://armature.tech/leaderboards/databases">tools</a> <a href="https://preseason.ai/rankings/devtools/database">track</a> the trends of what choices LLMs are most likely to make. Postgres dominates as the preferred database choice.</p><iframe src="https://planetscale.com/blog/the-moment-postgres-won/iframe#llm" title="Share of 32,955 LLM database recommendations, grouped by engine, with Postgres at 86%" loading="lazy"></iframe><p><em>Preseason database rankings, share of 32,955 LLM database decisions. Hosted services are counted under the engine they run.</em></p><p>So is Postgres&#x27; success due to its decades-old foundations, its ability to survive by fending off competitors, its timing in the agentic era, or something else? Was it deliberate or random? Let&#x27;s look backward from today through the pivotal moments that made Postgres feel inevitable, and try to pinpoint which one had the most profound impact.</p><h2 id="2025-here-comes-the-money"><a href="https://planetscale.com/blog/what-was-the-turning-point-for-postgres#2025-here-comes-the-money">2025: Here comes the money</a></h2><p>In 2025, investors and cloud providers put their money and time where developers were already going with acquisitions and infrastructure.</p><p>And, of course, PlanetScale (the household name in MySQL and Vitess) made PlanetScale Postgres generally available in September, bringing years of operational experience for one relational database to another.</p><p>Stack Overflow&#x27;s <a href="https://survey.stackoverflow.co/2025/technology#1-databases">yearly survey</a> saw Postgres take its biggest one-year jump in popularity, increasing 6.9 points. That increased preference by humans was not lost on LLMs, as agents chose Postgres when creating databases faster than humans ever had.</p><p>And so as developers looked less at the code, Postgres became the de facto choice as many people simply stopped caring (or arguing) about which database engine to choose.</p><p>Not only did agents choose Postgres, but it also became the most popular choice for building agentic applications. Developers didn&#x27;t need to choose a vector-specific database engine since pgvector adds that support to Postgres.</p><p>Right now, Postgres is well-funded, available everywhere, and the preferred choice for people and agents building almost any application.</p><p>But this isn&#x27;t <em>the</em> moment, rather, the growth explosion that previous decades had been leading up to.</p><h2 id="2023-postgres-takes-the-lead"><a href="https://planetscale.com/blog/what-was-the-turning-point-for-postgres#2023-postgres-takes-the-lead">2023: Postgres takes the lead</a></h2><p>Stack Overflow&#x27;s annual survey is a reasonable proxy for developer preference and had shown Postgres&#x27; increasing popularity for five years, but 2023 was the year it finally eclipsed MySQL (45.6% to 41.1%).</p><iframe src="https://planetscale.com/blog/the-moment-postgres-won/iframe#stack-overflow" title="Stack Overflow survey: share of developers using PostgreSQL, MySQL, and MongoDB, 2018–2026, with 2023 highlighted" loading="lazy"></iframe><p><em>Stack Overflow Developer Survey, share of all respondents</em></p><p>This could be seen as <em>the</em> moment Postgres ascended as it hasn&#x27;t relinquished this lead since (and as mentioned, the gap has only widened). This is remarkable compared with technology trends that regularly come and go.</p><p>But you might also only see this as the moment Postgres&#x27;s popularity was <em>visible</em>, not <em>inevitable</em>. And surveys show <em>stated</em> preferences, not <em>demonstrated</em> ones. Postgres never arrives at this moment if it doesn&#x27;t survive competition that threatened not only it, but an entire class of databases.</p><h2 id="201314-relational-holds-off-document-databases"><a href="https://planetscale.com/blog/what-was-the-turning-point-for-postgres#201314-relational-holds-off-document-databases">2013/14: Relational holds off document databases</a></h2><p>While Postgres spent many years competing with MySQL, document databases were threatening to overthrow both around this time. NoSQL databases like MongoDB promised flexible schemas with no migrations and data stored as JSON-like documents. It touted horizontal scaling and popularized (<a href="https://www.youtube.com/watch?v=b2F-DItXtZs">for better or worse</a>) the phrase &quot;web scale.&quot; Mongo was a tight fit for JavaScript and Node applications, and so the M in the MEAN/MERN stack (MongoDB) surged in popularity over the M in the LAMP stack (MySQL) of years earlier.</p><p>Relational databases simply couldn&#x27;t, or chose not to, compete.</p><p>Fighting back, Postgres added JSONB support in December 2014, at the height of MongoDB&#x27;s popularity. Something MySQL wouldn&#x27;t get for almost another year. Postgres was now able to store, but more importantly, <em>index</em> JSON-shaped data, making it fast to access. This didn&#x27;t make Postgres a direct competitor to document databases, but it at least covered much of their feature set and use cases.</p><blockquote><p>With the new JSONB data type for PostgreSQL, users no longer have to choose between relational and non-relational data stores: they can have both at the same time.</p></blockquote><p>— <a href="https://www.postgresql.org/about/news/postgresql-94-increases-flexibility-scalability-and-performance-1557/">Postgres 9.4 Release Announcement</a></p><p>Instead of using distinct services for different use cases, you could stuff all your data shapes and workloads in Postgres.</p><p>This kept Postgres relevant when it and its relational siblings were under threat, but Mongo was still the predominant choice. So at this time it&#x27;s hard to claim Postgres had <em>won</em>, but it certainly didn&#x27;t <em>die</em>.</p><p>It would take a few years for Postgres&#x27; popularity to overtake MongoDB&#x27;s. In the chart below you&#x27;ll see how Postgres was threatened by, and then surpassed MongoDB before opening a gap as MongoDB&#x27;s popularity declined.</p><iframe src="https://planetscale.com/blog/the-moment-postgres-won/iframe#db-engines" title="DB-Engines popularity scores for PostgreSQL, MySQL, and MongoDB, 2013–2026, with 2017 highlighted" loading="lazy"></iframe><p><em>DB-Engines popularity score, each January, plus October 2026</em></p><p>JSONB may have kept developers on Postgres, but it didn&#x27;t bring them there. Much of the Rails and Python community had already moved to Postgres years earlier for one main reason: convenience.</p><h2 id="2011-heroku-makes-postgres-the-default"><a href="https://planetscale.com/blog/what-was-the-turning-point-for-postgres#2011-heroku-makes-postgres-the-default">2011: Heroku makes Postgres the default</a></h2><p>If you&#x27;re relatively new to web application development, you might not remember a time when databases couldn&#x27;t just be created on demand, managed by a cloud platform.</p><p>The <em>peak</em> of technology at one time was one-click WordPress installs on your host&#x27;s cPanel along with phpMyAdmin for hosted MySQL.</p><p>Heroku bet on making creating and interfacing with databases easier than ever before, and chose Postgres as the engine to offer. First offered in 2007, Heroku Postgres launched as a standalone service in November 2011. Remarkably, the product team responsible had no strong opinion of which engine to offer, it just so happened that one engineer seemed to like it.</p><blockquote><p>Most folks didn&#x27;t have strong opinion, but one of our security/ops engineers chimed in &quot;Postgres has always had a good record of being safe and reliable for data, I&#x27;d go with it.&quot; And with that, we were building and launching Heroku Postgres.</p></blockquote><p>— <a href="https://www.craigkerstiens.com/2022/05/18/unfinished-business-with-postgres/">Unfinished Business with Postgres</a>, Craig Kerstiens</p><p>Developers followed not necessarily because they loved Postgres, but because they preferred Heroku&#x27;s convenience.</p><p>Heroku also put money into Postgres development. Funding work to improve <code>pg_stat_statements</code>, working directly with Postgres developers on JSON and JSONB, pushing for <code>DATABASE_URL</code> connection strings, and later hiring contributors to work on upstream Postgres.</p><p>The audience and demand that Heroku created for Postgres attracted other providers. AWS launched RDS Postgres in 2013, which was inspired by what Heroku had done.</p><p>Heroku&#x27;s investment in Postgres would pay off in the following years, with its biggest one year spike (36%) on DB-Engines rankings in 2013.</p><p>Now in a &quot;<a href="https://www.heroku.com/blog/an-update-on-heroku/">sustaining engineering</a>&quot; model, Heroku&#x27;s momentum didn&#x27;t last. But the deliberate choice to make cloud-hosted databases easy, and the almost random choice of Postgres as the database engine, built an audience with those expectations. It could be the moment that led to Postgres&#x27;s massive adoption today.</p><p>(If you&#x27;re still on Heroku Postgres, we have tooling to help get you onto PlanetScale Postgres <em>fast</em> and with minimal downtime. Check out <a href="https://planetscale.com/docs/postgres/imports/heroku">Migrate from Heroku to PlanetScale</a> for more details.)</p><p>There was little unique about Postgres that made it the choice for Heroku, so what stopped MySQL from being that choice? Especially since it dominated the early web. Its ownership perhaps played a pivotal role.</p><h2 id="2010-did-postgres-increase-or-mysql-decrease"><a href="https://planetscale.com/blog/what-was-the-turning-point-for-postgres#2010-did-postgres-increase-or-mysql-decrease">2010: Did Postgres increase or MySQL decrease?</a></h2><p>Sun acquired MySQL in 2008; Oracle acquired Sun in January 2010. On the same day as the acquisition was announced in 2009, MySQL&#x27;s creator forked MySQL into MariaDB because he didn&#x27;t trust Oracle with it. Suddenly, the most popular open-source database fell under the purview of the largest proprietary database vendor, and its community began to fragment. While this acquisition could&#x27;ve been seen as a positive signal that MySQL would be well funded, the move cast doubts over its future governance and direction. The sort of doubt that makes developers think twice before choosing a database.</p><p>While the Oracle deal spooked the community, MySQL adoption continued to grow for years afterward.</p><p>Curiously, the European Commission named Postgres as a viable alternative when it approved the deal.</p><p>Postgres still lagged behind MySQL on some features, but was catching up. Postgres 9.0 shipped in late 2010 with built-in replication, considered one of the last remaining practical reasons to choose MySQL over Postgres.</p><p>Despite this, in the same year YouTube created Vitess to scale MySQL beyond a single primary database. MySQL was boasting performance and scale that few Postgres deployments had attempted.</p><p>So while Postgres&#x27; largest competitor began to lose momentum in developer communities, MySQL still did (and still does) run some of the industry&#x27;s largest and most mature workloads for the web&#x27;s most popular applications such as Facebook and WordPress.</p><p>This was the moment Postgres became the most likely alternative to MySQL.</p><p>But it could never have reached this position if it had simply gone away years earlier.</p><h2 id="1994-96-one-foot-in-the-grave"><a href="https://planetscale.com/blog/what-was-the-turning-point-for-postgres#1994-96-one-foot-in-the-grave">1994-96: One foot in the grave</a></h2><p>Postgres&#x27; popularity was never assured. 30 years ago it was almost dead. Less than a decade after Michael Stonebraker had created POSTGRES at Berkeley, he moved on, co-founding Illustra in 1992 to sell a commercial version and so the research project ended with version 4.2 in 1994.</p><p>Two grad students, Andrew Yu and Jolly Chen, needed a database for other projects and began creating Postgres95 from a fork of the final release from Berkeley.</p><p>They replaced Postgres&#x27; own query language PostQUEL with SQL, trimmed the codebase by about 25%, and improved performance 30-50%. What they had created got attention and was made publicly available.</p><blockquote><p>At the time, we had no idea where we were going with the project. By the spring of 1995 however, it had occurred to us that the Internet user community really needed an open source, SQL-based multiuser database.</p></blockquote><p>— Yu and Chen, in the foreword to <a href="https://momjian.us/main/writings/pgsql/aw_pgsql_book/node5.html">PostgreSQL: Introduction and Concepts</a> by Bruce Momjian</p><p>In 1996, Bruce Momjian found the Postgres95 project with only one part-time maintainer. He and Marc Fournier began creating patches, issuing releases and renamed the project PostgreSQL. That volunteer group became the core team.</p><p>This organizational structure combined with its already permissive license, Postgres, unlike MySQL, has never had a single owner. That is why every cloud can provide, fork, and extend Postgres as it likes.</p><p>In this moment, the seeds of what would make Postgres popular were sown, but MySQL would still dominate open-source relational databases on the web for the next 15 years. Postgres&#x27; popularity would have to wait until after the turn of the new millennium, but then perhaps <em>Postgres&#x27; plans are measured in centuries</em>.</p><h2 id="1986-was-it-destiny"><a href="https://planetscale.com/blog/what-was-the-turning-point-for-postgres#1986-was-it-destiny">1986: Was it destiny?</a></h2><p>Was Postgres always destined to succeed thanks to its original design?</p><p>From the start, Postgres was designed to be extensible, and its rich ecosystem of extensions is critical to its success. You don&#x27;t get &quot;just use Postgres&quot; almost 40 years later without it.</p><p>The permissive BSD-style license issued by Berkeley played a massive role in widespread adoption. Today&#x27;s PostgreSQL License is similar.</p><p>Some might argue this flexibility should attribute success to the Postgres wire protocol, not only Postgres itself. PlanetScale offers Postgres on a range of compute and storage options, plus custom extensions like Database Traffic Control™ and TIN search. While other providers completely change the storage method or sell opinionated configurations. There&#x27;s Postgres in the browser. Of course Postgres is being rewritten in Rust. And yet, it&#x27;s all Postgres.</p><h2 id="the-work-still-left-to-do"><a href="https://planetscale.com/blog/what-was-the-turning-point-for-postgres#the-work-still-left-to-do">The work still left to do</a></h2><p>Some use cases for Postgres remain unsolved despite its overwhelming popularity. Multiple vendors are approaching horizontal sharding, for example. Meanwhile, Vitess has powered sharded MySQL since 2010 at the likes of Slack and GitHub.</p><p>At PlanetScale, <a href="https://neki.dev/">we launched Neki</a> in platform preview in September 2026. It is a net-new platform informed by Vitess&#x27;s (sharded MySQL) design and our experience running it in production. As for performance, Neki has already sustained <a href="https://planetscale.com/blog/118-million-queries-per-second-on-neki">118 million queries per second</a> across 512 shards.</p><p>Postgres isn&#x27;t perfect, but it&#x27;s everywhere, and we&#x27;re doing our part for it to catch up to MySQL&#x27;s proven scale.</p><h2 id="what-moment-do-you-think-it-was"><a href="https://planetscale.com/blog/what-was-the-turning-point-for-postgres#what-moment-do-you-think-it-was">What moment do you think it was?</a></h2><p>Along this journey, some <em>deliberate</em> design choices played a role in Postgres&#x27; success. Others, like Heroku&#x27;s choice of Postgres, seemed almost <em>random</em>.</p><p>In fairness, it&#x27;s not as though Postgres &quot;deserved&quot; its current status until recently. MySQL dominated the early web for a number of reasons. It was designed for short, simple queries, which were enough to power the web&#x27;s biggest applications at the time. MySQL could also be run on Windows (the most popular developer environment of the time). Meanwhile, Postgres was more focused on correctness, full transactions, and complex queries.</p><p>In the era of &quot;Web2&quot; applications, document databases solved real performance problems that relational databases exposed.</p><p>And for Postgres to succeed didn&#x27;t mean MySQL had to fail. Famously, <a href="https://www.uber.com/us/en/blog/postgres-to-mysql-migration/">Uber migrated from Postgres <em>to</em> MySQL</a> in 2016. MySQL and Vitess continue today and are still a growing part of PlanetScale.</p><p>But as of right now, you won&#x27;t be on your own if you <em>just use Postgres</em>.</p><p>Which moment resonates most with you, or do you think there&#x27;s another reason Postgres is as popular as it is today?</p>]]></content>
    <summary><![CDATA[Postgres is the most popular database choice among developers. Postgres is the default choice for agents, powering countless applications where those new to app building don't even know what a database is. Every major cloud offers hosted Postgres.]]></summary>
  </entry>
  <entry>
    <title>Neki update: $50 Metal, read-only replicas, Azure, and more</title>
    <link href="https://planetscale.com/blog/neki-updates-and-preparing-for-production"/>
    <id>https://planetscale.com/blog/neki-updates-and-preparing-for-production</id>
    <published>2026-10-20T04:00:00.000Z</published>
    <updated>2026-10-20T04:00:00.000Z</updated>
    <author>
      <name>Nick Van Wiggeren</name>
    </author>
    <category term="product"/>
    <category term="neki"/>
    <content type="html"><![CDATA[<p>Neki, our sharded Postgres, has been in platform preview for about a month. The team continues to work towards the path to production-readiness, and we&#x27;ve added quite a few new features and capabilities since launch.</p><p>Here&#x27;s a quick look at what&#x27;s landed since the preview opened and how you can start evaluating Neki for your workload today.</p><h2 id="whats-shipped"><a href="https://planetscale.com/blog/neki-updates-and-preparing-for-production#whats-shipped">What&#x27;s shipped</a></h2><p>We&#x27;ve recently added both read-only replicas and smaller Metal instances to Neki starting at just $50 per month.</p><p><a href="https://planetscale.com/changelog/neki-read-only-replicas">Read-only replicas</a> were a hotly-requested feature for Postgres, particularly for customers with a large, global userbase. Neki now also supports read-only replicas for shards in your cluster.</p><p>We also <a href="https://planetscale.com/changelog/neki-metal-m-10-to-m-160">now support smaller Metal node sizes</a>, going all the way down to database nodes with 1/8th vCPU, 1GB RAM, and 10GB of locally-attached NVMe SSD.</p><p>You can try both of these capabilities on Neki in PlanetScale today. These are just a few amongst many others, including:</p><ul><li><strong><a href="https://planetscale.com/changelog/neki-extensions-terraform-cli">Manage Neki extensions with Terraform and the CLI</a></strong> (Sept 18). Enable extensions by name with <code>extensions</code> in a <code>planetscale_neki_configuration_profile</code> resource or with <code>pscale branch config-profile update --extensions</code>, and change their settings in the same update.</li><li><strong><a href="https://planetscale.com/changelog/mcp-branch-metrics">Branch metrics in the PlanetScale MCP server</a></strong> (Oct 9). <code>planetscale_get_branch_metrics</code> pulls CPU, memory, disk, replication lag, and connections into your AI agent, or wherever you connect to your infrastructure via MCP. It works for Neki, Postgres, and Vitess.</li><li><strong><a href="https://planetscale.com/changelog/planetscale-on-azure">PlanetScale on Azure</a></strong> (Oct 13). You can now create Neki and Postgres databases in Azure regions, alongside AWS and Google Cloud.</li><li><strong><a href="https://planetscale.com/changelog/neki-router-parameters-terraform">Neki router parameters in Terraform</a></strong> (Oct 14). Terraform provider v1.13.0 adds parameter management to <code>planetscale_neki_router</code>, and the <code>planetscale_databases</code> data source can now filter by <code>kind</code> (<code>mysql</code>, <code>postgresql</code>, or <code>neki</code>).</li><li><strong><a href="https://planetscale.com/changelog/cli-parameters-need-update">CLI shows which parameters need an update</a></strong> (Oct 14). CLI v0.346.0 adds a &quot;requires update&quot; column for Neki configuration profiles, admins, and sidecars, plus a <code>requires_update</code> field in JSON output.</li><li><strong><a href="https://planetscale.com/changelog/postgres-neki-huge-pages">Huge pages for Neki and Postgres</a></strong> (Oct 15). Set <code>huge_pages</code> to <code>on</code> in a configuration profile&#x27;s Parameters tab on supported cluster sizes. The change requires a restart.</li></ul><h2 id="under-the-hood-query-layer"><a href="https://planetscale.com/blog/neki-updates-and-preparing-for-production#under-the-hood-query-layer">Under the hood: query layer</a></h2><p>Much of the engineering effort since preview has gone into the query layer: making more of your existing SQL run on a sharded database without changes, and making the standard Postgres tools you already use work against Neki.</p><p>The team has merged more than 650 changes since the preview opened. A few more highlights:</p><ul><li>More of your SQL just works. INSERT ... SELECT ... ON CONFLICT, cross-shard <code>UPDATE ... FROM</code>, <code>DELETE ... USING</code> and <code>MERGE</code>, correlated <code>EXISTS</code> almost anywhere in a query, <code>ARRAY(SELECT ...)</code>, SQL cursors, <code>LISTEN</code>/<code>NOTIFY</code>, materialized views, and PL/pgSQL exception handlers are all now supported.</li><li>Export with standard tools. <code>COPY ... TO STDOUT</code> now works on sharded tables in text, CSV, and binary, so pg_dump and other export tools can read data out of a sharded Neki database.</li><li>Faster bulk writes. Distributed <code>INSERT ... SELECT</code> is about 76x faster than at launch, and COPY ingest is roughly 5x faster.</li><li>See how your query runs on every shard. <code>EXPLAIN (NEKI_PG_PLAN)</code> shows Neki&#x27;s distributed plan together with the Postgres plan each shard ran. The output follows Postgres&#x27;s own EXPLAIN format, so pgAdmin, DBeaver, <code>explain.dalibo.com</code>, and <code>explain.depesz.com</code> can read it.</li></ul><h2 id="start-evaluating-now"><a href="https://planetscale.com/blog/neki-updates-and-preparing-for-production#start-evaluating-now">Start evaluating now</a></h2><p>If you&#x27;re running Postgres and expect to need sharding or any other Neki features like online schema changes or no downtime version upgrades, now is a good time to start the conversation. Email us at <a href="mailto:neki@planetscale.com">neki@planetscale.com</a> or <a href="https://planetscale.com/contact">fill out the form</a>, and we&#x27;ll set up a call with our solutions team.</p><p>If you want to learn more about Neki, we recommend starting with <a href="https://planetscale.com/docs/neki/when-to-shard">When to shard</a>, <a href="https://planetscale.com/docs/neki/best-practices">Neki best practices</a>, and <a href="https://planetscale.com/docs/neki/data-topology">Data topology</a>.</p>]]></content>
    <summary><![CDATA[Postgres compatibility, read-only replicas, smaller Metal instances, Azure, and more have landed for Neki since platform preview.]]></summary>
  </entry>
  <entry>
    <title>PlanetScale is now available on Azure</title>
    <link href="https://planetscale.com/blog/planetscale-is-now-on-azure"/>
    <id>https://planetscale.com/blog/planetscale-is-now-on-azure</id>
    <published>2026-10-13T00:00:00.000Z</published>
    <updated>2026-10-13T00:00:00.000Z</updated>
    <author>
      <name>Joe Miller</name>
    </author>
    <author>
      <name>Matt Layher</name>
    </author>
    <category term="product"/>
    <category term="company"/>
    <content type="html"><![CDATA[<p>PlanetScale is now available on Microsoft Azure. Starting today, you can create PlanetScale Postgres and Neki databases in select Azure regions, alongside the AWS and Google Cloud regions we already support. Vitess databases are not currently available on Azure.</p><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/create-database-azure-BMkK-98L.png?auto=compress%2Cformat"><img alt="Creating a PlanetScale Postgres database in the Azure centralus region" src="https://planetscale-images.imgix.net/assets/create-database-azure-BMkK-98L.png?auto=compress%2Cformat" width="2922" height="1634" loading="lazy"></picture></p><h2 id="why-azure"><a href="https://planetscale.com/blog/planetscale-is-now-on-azure#why-azure">Why Azure?</a></h2><p>Many teams run their apps on Azure, and we&#x27;ve received consistent requests, especially over the past year, to bring PlanetScale to where they&#x27;re building. Now those teams can use PlanetScale alongside all their other Azure compute and infrastructure.</p><h2 id="whats-included"><a href="https://planetscale.com/blog/planetscale-is-now-on-azure#whats-included">What&#x27;s included?</a></h2><p>Databases on Azure get the same PlanetScale features you use on our other clouds: high availability with a primary and replicas spread across 3 availability zones, Query Insights, schema recommendations, automated backups, and more. That includes Metal clusters with locally attached NVMe storage, the fastest way to run databases  in the cloud.</p><h2 id="supported-azure-regions"><a href="https://planetscale.com/blog/planetscale-is-now-on-azure#supported-azure-regions">Supported Azure regions</a></h2><p>Azure support is currently available in the following regions:</p><ul><li><code>centralus</code> (Iowa, USA)</li><li><code>eastus2</code> (Virginia, USA)</li><li><code>westeurope</code> (Netherlands)</li></ul><p>If you&#x27;d like to see PlanetScale in other Azure regions, <a href="https://ps-regions.io/">let us know</a>. See the <a href="https://planetscale.com/docs/plans/regions">regions documentation</a> for the full list across all cloud providers.</p><h2 id="what-it-took"><a href="https://planetscale.com/blog/planetscale-is-now-on-azure#what-it-took">What it took</a></h2><p>Bringing PlanetScale to a new cloud took significant time, particularly in testing and ensuring it behaves just as seamlessly on Azure as it does on AWS and GCP. Every cloud has its quirks, and Azure is no exception.</p><p>Kubernetes pod networking is a good example. PlanetScale runs databases on Kubernetes, and every database pod needs its own IP address on the network. We wanted those addresses to come from the Azure virtual network directly, with native routing and no overlay for maximum performance and low latency.</p><p>The simple approach is to request one IP from Azure per pod, which causes two problems. Azure caps a virtual network at 65,536 private IP addresses, which would limit the whole network to about 65,000 pods. It also puts the Kubernetes API server in the path of every pod start, which slows things down under load.</p><p>We solved both by handing out addresses in blocks. Each node gets blocks of 16 IPs (<code>/28</code> prefixes) on its network interface, and Azure counts each block as a single address toward the cap. That increases our overall IP capacity by 16x, to over a million pod IPs per network. A background service on each node tracks its blocks, and a lightweight CNI plugin assigns pod IPs from them locally, so the API server stays out of the way. When a node gets down to 8 free addresses, it grabs another block, up to 256 blocks (4,096 pod IPs) per node.</p><p>This sounds like a simple solution, but it took a surprising amount of custom work to get just right.</p><p>Azure had a few additional networking challenges along the way. <code>/28</code> is the only block size it offers, so the design had to work around that. Older versions of the network interface API don&#x27;t return prefixes at all, and the block&#x27;s range comes back in a field normally used for a single address. There&#x27;s also a chicken-and-egg problem: system pods need IPs before the Kubernetes operator that manages the blocks is running. To handle that, the operator has a bootstrap mode that runs on the host network.</p><p>In scale testing, one cluster ran over 6,700 pods across more than 100 node pools, with the busiest nodes holding 15 blocks (240 IPs) each.</p><p>This is just one of many pieces we had to carefully construct to make PlanetScale on Azure a seamless experience for our customers. Storage, load balancing, identity, and backups all needed the same level of care. All of that work culminates in today&#x27;s launch.</p><h2 id="getting-started"><a href="https://planetscale.com/blog/planetscale-is-now-on-azure#getting-started">Getting started</a></h2><p>To create a database on Azure, choose Azure as the cloud provider when you create a new database, then select a region. Existing databases can be migrated to Azure by contacting <a href="https://support.planetscale.com/">support</a>.</p><p>If you have questions or want help planning a move, <a href="https://planetscale.com/contact">get in touch</a>.</p>]]></content>
    <summary><![CDATA[PlanetScale Postgres and Neki databases can now be deployed on Microsoft Azure]]></summary>
  </entry>
  <entry>
    <title>What today's software owes to Bronze Age clocks</title>
    <link href="https://planetscale.com/blog/leaky-buckets-in-software-explained"/>
    <id>https://planetscale.com/blog/leaky-buckets-in-software-explained</id>
    <published>2026-10-07T00:00:00.000Z</published>
    <updated>2026-10-07T00:00:00.000Z</updated>
    <author>
      <name>Simeon Griggs</name>
    </author>
    <category term="engineering"/>
    <category term="postgres"/>
    <content type="html"><![CDATA[<p>Here&#x27;s a deceptively simple question: should this function execute?</p><p>Sometimes, the answer is obvious. Is the user logged in? Does their role have the required permissions?</p><p>Sometimes it&#x27;s less obvious. Are there sufficient resources available? Is this work a higher priority than everything else?</p><p>There are many names for the mechanisms that block or allow actions in software. Most commonly they are referred to as <strong>admission control</strong>. Perhaps you&#x27;ll be familiar with a <strong>leaky bucket</strong> implementation.</p><h2 id="a-brief-history-of-leaky-buckets"><a href="https://planetscale.com/blog/leaky-buckets-in-software-explained#a-brief-history-of-leaky-buckets">A brief history of leaky buckets</a></h2><p>Engineering applications for leaky buckets predate computers. From around 1600 BC the Babylonians, Egyptians, and Persians all used vessels with a small hole in the bottom as primitive clocks, measuring elapsed time by the volume of the container as it drained at a constant rate.</p><iframe src="https://planetscale.com/blog/leaky-buckets-in-software-explained/iframe#water-clock" title="Animated: a simplified isometric model of Ctesibius&#x27; water clock" loading="lazy"></iframe><p>By around 200 BC the Greeks had advanced leaky buckets into accurate clocks. A floating regulator kept water flowing steadily from one bucket into a second, where a rising float moved a pointer to show the hour. A siphon emptied the second bucket once it was full. Most notably, Ctesibius added gears to regularly advance each &quot;tick&quot; of the clock, turning the display which indicated the current season.</p><p>A mechanical movement driven by a leaky bucket was born, and it became the gold standard of timekeeping for centuries.</p><p>Water-based clocks were used as a form of admission control. In Athenian courts, the length of time a speaker had to plead their case was measured by the time water took to drain from a vessel. The amount of water poured into the vessel was determined by the severity of the case.</p><p>Finally, in the computer age, Jonathan Turner is said to have used the term &quot;leaky bucket&quot; first in 1986, writing &quot;New directions in communications&quot; for IEEE Comms Magazine. The piece describes how a system can police the pace at which packets are sent over broadband connections. (If you haven&#x27;t read it, spoiler: it&#x27;s not much slower than your connection at home today.)</p><h2 id="leaky-buckets-in-software"><a href="https://planetscale.com/blog/leaky-buckets-in-software-explained#leaky-buckets-in-software">Leaky buckets in software</a></h2><p>There are two kinds of leaky buckets in software, to implement a <strong>meter</strong> or a <strong>queue</strong>.</p><p>In both, each unit of &quot;work&quot; is assigned a value which is checked against the current volume of a &quot;bucket.&quot; If the bucket lacks capacity for the size of new work, that work is rejected. Otherwise the work is allowed and its value adds to the bucket&#x27;s current volume. The bucket drains (or leaks, if you will), so over time, new work can&#x27;t be admitted faster than the bucket drains. The drain rate is based on time elapsed, not on the completion of work.</p><p>When used as a <strong>meter</strong>, the bucket defines if and how much work is permitted to <em>immediately proceed</em>. As a <strong>queue</strong>, the bucket defines the volume of work that can <em>wait to proceed</em>, but work only begins as it drains from the bucket.</p><p>In this post we&#x27;ll focus on leaky buckets as a meter.</p><p>Typically, leaky buckets are implemented in software to keep systems healthy. A sort of resource management to ensure the system is not overwhelmed.</p><p>It&#x27;s not hard to imagine this being useful in a database. Imagine being able to block or allow queries, before they execute, based on available resources or concurrency limits. One can dream!</p><iframe src="https://planetscale.com/blog/leaky-buckets-in-software-explained/iframe" title="Interactive: a leaky bucket with adjustable volume and drain rate" loading="lazy"></iframe><p><em>The leaky bucket can be tweaked by modifying its volume and the rate at which it drains.</em></p><p>At its core a leaky bucket prevents work, but it also forces us to reason about the total volume of work that results in a block, how quickly more capacity becomes available, and how to handle the expected failure state when work is rejected.</p><h3 id="leaky-buckets-in-api-design"><a href="https://planetscale.com/blog/leaky-buckets-in-software-explained#leaky-buckets-in-api-design">Leaky buckets in API design</a></h3><p>Shopify&#x27;s GraphQL Admin API implements rate limiting with a <a href="https://shopify.dev/docs/apps/build/apis/graphql-admin/rate-limits">documented leaky bucket</a>. Each app on each store gets a bucket with a fixed size and restore rate.</p><p>Each request costs a different amount based on what the query asks for, not how many requests are made. Before a query runs, the bucket must have room for its estimated cost. Once it completes, the bucket is refunded or charged any difference between the estimated and actual cost. Apps can burst faster than the restore rate until the bucket has no room left, at which point requests are throttled.</p><p>Responses include the current state of the bucket, so apps can slow down before they&#x27;re throttled and treat throttling as an expected outcome, not a surprise.</p><h3 id="classification-as-admission-control"><a href="https://planetscale.com/blog/leaky-buckets-in-software-explained#classification-as-admission-control">Classification as admission control</a></h3><p>Now let&#x27;s consider the AI age. Jev, a &quot;System One&quot; model (perhaps better named a &quot;<a href="https://x.com/Mappletons/status/2101560333441610133">Decision Model</a>&quot;), recently launched, making classification through inference cheap and fast. It could classify &quot;should this work proceed or not&quot; based on a predefined set of options and return a response in hundreds of milliseconds.</p><div class="mb-3 border p-3 border-blue-600 dark:border-blue-500"><p><span class="bg-blue-600 px-sm text-white dark:bg-blue-500 dark:text-black">Note</span></p><p>Fun full-circle fact: In 1907, the French scientist Lapicque modeled neurons as a charge that accumulates, leaks away, and fires at a threshold, later called the &quot;leaky integrate-and-fire&quot; model. So something like a leaky bucket has long been used to describe <strong>neurons</strong>, making it part of the origin story of <strong>neural networks</strong>, and so of Jev.</p></div><p>Whether our decision gate is <em>mechanical</em> (leaky bucket) or requires <em>inference</em> (Jev), the requirement is the same: answering &quot;should this proceed?&quot;</p><h3 id="low-cost-throttling"><a href="https://planetscale.com/blog/leaky-buckets-in-software-explained#low-cost-throttling">Low cost throttling</a></h3><p>One of the great benefits of leaky buckets in software is how cheap they are. What we&#x27;ve described as a slowly draining bucket isn&#x27;t a long-running process that is using CPU to &quot;drain&quot;.</p><p>Simply put, a bucket is a stateful object that holds two values:</p><ol><li><strong>how full</strong> it was the last time anyone looked</li><li><strong>when</strong> that was</li></ol><p>From those values, you can work out how full the bucket is now:</p><div class="code-block"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span>level_now = max(0, level_then - drain_rate × (now - then))</span></span>
<span class="line"><span></span></span></code></pre></div></div><p>Any work rejected or admitted by the bucket updates its current state. In this way, buckets are lazily drained (as in, only when checked) and empty buckets hold no values.</p><h2 id="admission-controls-and-databases"><a href="https://planetscale.com/blog/leaky-buckets-in-software-explained#admission-controls-and-databases">Admission controls and databases</a></h2><p>Just like hardware, operating systems, applications, and ancient Greeks, databases benefit from leaky buckets.</p><p>However, open-source databases like Postgres and MySQL don&#x27;t have this functionality baked in.</p><p>One of the most common failure modes for databases in production is the inability to deliberately reject work they cannot complete. Blast a billion queries at your typical relational database, and it&#x27;ll try its best to execute them. Success isn&#x27;t likely. Some hardware, configuration, or connection limitation will unwittingly play the role of an admission control system and start blocking work in some unhandled, undesirable way.</p><p>Some proprietary databases have a form of resource management so that workloads can be throttled (but not rejected). For example, in 1999 the Oracle Database Resource Manager added mapping rules to sessions for users, services, clients, and more, which could then be used to apply limits on things like resource use and concurrency.</p><p>In 2008, SQL Server added the SQL Server Resource Governor, which added classifier functions to sessions that can then apply rules to queries in that session.</p><p>Postgres has some configuration options to control expensive queries that have <em>already</em> consumed resources, such as <code>statement_timeout</code>, but nothing to prevent expensive work before it happens. And so in 2026, PlanetScale brought decision gates to Postgres with Database Traffic Control®.</p><h2 id="database-traffic-control"><a href="https://planetscale.com/blog/leaky-buckets-in-software-explained#database-traffic-control">Database Traffic Control</a></h2><p>The health of your Postgres database is laid bare at the mercy of your applications. An unexpected connection storm or <a href="https://planetscale.com/blog/when-the-postgres-query-planner-goes-rogue">failure of the query planner</a> can ask more of your database than it can reasonably be expected to handle.</p><p>To protect your Postgres database from your application (and at times, from itself), we built Traffic Control, admission control for Postgres. In it, resource budgets determine how many resources or how much concurrency one or many queries can consume.</p><p>Each budget admits or blocks queries that match a specified set of tags. Those tags can be specified as comments in the query, or they can refer to the user or application that sent it. If the resource budget determines the query should not proceed, it will log a warning or block it, depending on your resource budget configuration.</p><p>Creating a resource budget opts you into an expected failure state, so it forces you to reason about the behavior your application should exhibit when queries are blocked. For this reason, we recommend creating a new budget in warning mode first, monitoring how much traffic is affected, preparing your application for blocked queries, and then updating the mode.</p><h3 id="admission-controls-but-for-traffic"><a href="https://planetscale.com/blog/leaky-buckets-in-software-explained#admission-controls-but-for-traffic">Admission controls but for traffic</a></h3><p>You configure <a href="https://planetscale.com/docs/postgres/traffic-control/concepts#resource-budget-limits">three major settings</a> on a resource budget.</p><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/server-share-burst-limit-DGMkwJno.png?auto=compress%2Cformat"><source media="(prefers-color-scheme: dark)" srcSet="https://planetscale-images.imgix.net/assets/server-share-burst-limit-darkmode-DqJFlt7P.png?auto=compress%2Cformat"><img alt="Server share and burst limit settings on a resource budget" src="https://planetscale-images.imgix.net/assets/server-share-burst-limit-DGMkwJno.png?auto=compress%2Cformat" width="1244" height="569" loading="lazy"></picture></p><p><strong>Server share and burst limit</strong>, the token* bucket. Server share determines how fast the bucket replenishes with tokens, expressed as a percentage of server resources. The burst limit sets the maximum capacity of the bucket, expressed in whole-server seconds.</p><p>Because a database doesn&#x27;t know the cost of a query before execution, Traffic Control estimates its cost based on the query plan and historical behavior of queries with that shape. If the budget has sufficient capacity the query proceeds. After execution, the cost of the query is calculated and any difference is either refunded or charged to the token bucket.</p><p>Why is the refill rate measured in server capacity instead of seconds? Because not all time spent executing a query is equal. A query that took 8 cores a single second is different from a query that took one core a single second. Consider different server sizes as well: a 25% server share means a quarter of your server&#x27;s capacity drains back every second, whether that server has 2 cores or 64.</p><div class="mb-3 border p-3 border-blue-600 dark:border-blue-500"><p><span class="bg-blue-600 px-sm text-white dark:bg-blue-500 dark:text-black">Note</span></p><p>*Hold on, <strong>token</strong> bucket?</p><p>A <em>token</em> bucket works the same as a <em>leaky</em> bucket, but with a reversed metaphor. The bucket starts filled with &quot;tokens&quot; and each piece of work is assigned a &quot;cost.&quot; Work is only admitted if there are sufficient tokens remaining for that work. Tokens refill over time. It&#x27;s a bit easier to reason about the remaining capacity of a resource budget in terms of a bucket&#x27;s remaining tokens than its current fill level.</p><p>Naming things, right?</p></div><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/per-query-limit-ZNVEaYkv.png?auto=compress%2Cformat"><source media="(prefers-color-scheme: dark)" srcSet="https://planetscale-images.imgix.net/assets/per-query-limit-darkmode-BXdR_omg.png?auto=compress%2Cformat"><img alt="Per-query limit setting on a resource budget" src="https://planetscale-images.imgix.net/assets/per-query-limit-ZNVEaYkv.png?auto=compress%2Cformat" width="1244" height="307" loading="lazy"></picture></p><p><strong>Per-query limit</strong> sets an upper limit on the maximum capacity a single query can consume. This makes an admission-control decision directly on a single query instead of measuring it against available capacity in a bucket.</p><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/max-concurrent-workers-DrvFI6m-.png?auto=compress%2Cformat"><source media="(prefers-color-scheme: dark)" srcSet="https://planetscale-images.imgix.net/assets/max-concurrent-workers-darkmode-8SARE59j.png?auto=compress%2Cformat"><img alt="Maximum concurrent workers setting on a resource budget" src="https://planetscale-images.imgix.net/assets/max-concurrent-workers-DrvFI6m-.png?auto=compress%2Cformat" width="1244" height="341" loading="lazy"></picture></p><p><strong>Maximum concurrent workers</strong> similarly controls the resources a single query can consume, but measures it by available workers instead of execution time.</p><p>A query may be targeted by multiple resource budgets and must satisfy all of them to proceed.</p><p>For specific scenarios where resource budgets help, along with how to tag queries in your codebase, see <a href="https://planetscale.com/blog/patterns-for-postgres-traffic-control">Patterns for Postgres Traffic Control</a>.</p><h2 id="summary"><a href="https://planetscale.com/blog/leaky-buckets-in-software-explained#summary">Summary</a></h2><p>Admission control forces you to decide what should happen when work can&#x27;t proceed, and leaky buckets have been a cheap way to make that decision for a very long time. Traffic Control makes that decision for Postgres before an expensive query runs, not after.</p><p>Get started with <a href="https://planetscale.com/docs/postgres/traffic-control">Database Traffic Control</a></p>]]></content>
    <summary><![CDATA[Admission controls in software determine what does or doesn't happen next, and the most common implementation has ancient roots.]]></summary>
  </entry>
  <entry>
    <title>Building a faster, lazier router for Postgres</title>
    <link href="https://planetscale.com/blog/designing-neki-for-performance"/>
    <id>https://planetscale.com/blog/designing-neki-for-performance</id>
    <published>2026-10-01T00:00:00.000Z</published>
    <updated>2026-10-01T00:00:00.000Z</updated>
    <author>
      <name>Dirkjan Bussink</name>
    </author>
    <category term="engineering"/>
    <category term="neki"/>
    <content type="html"><![CDATA[<p>Nothing is as fast as not doing anything. That sounds obvious, but it is also surprisingly easy to forget when building software.</p><p><a href="https://planetscale.com/blog/announcing-neki">Neki</a> adds a layer between a PostgreSQL client and PostgreSQL. We need that layer to route queries to shards and to make <a href="https://planetscale.com/blog/making-768-servers-look-like-1">many PostgreSQL servers look like one</a>. The downside is that every query now has another network hop and has to pass through the <a href="https://planetscale.com/blog/what-is-a-neki-router">router</a>.</p><p>We can&#x27;t make that hop disappear, so a lot of the performance work in Neki comes down to what we can avoid doing while the query passes through it. If the router doesn&#x27;t need to understand a result, why decode it? If it only needs one column, why decode the other ten columns in the same row?</p><p>The key part here is that we can design this to be lazy and composable. Walking the PostgreSQL messages in a response does not mean we also need to construct rows. Finding the rows does not mean we need to decode their columns either. Even if the router needs one value, the rest of the row can stay as protocol bytes.</p><h2 id="why-not-decode-everything-up-front"><a href="https://planetscale.com/blog/designing-neki-for-performance#why-not-decode-everything-up-front">Why not decode everything up front?</a></h2><p>The usual way to build a layer like this is to parse whatever comes over the wire into your own types as soon as it arrives. Every row becomes a list of values, and the rest of the code only ever deals with those. It&#x27;s a sensible default because it gives the rest of the system one consistent thing to work with.</p><p>Vitess, the MySQL sharding system we maintain, works this way, so it&#x27;s a useful comparison. Vitess sends query results between its components using protobuf. Leaving out the fields that aren&#x27;t important here, <a href="https://github.com/vitessio/vitess/blob/main/proto/query.proto"><code>QueryResult</code> and <code>Row</code></a> look like this:</p><div class="code-block" data-language="json"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">message QueryResult </span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">{</span></span>
<span class="line"><span style="--shiki-light:#C11027;--shiki-dark:#FF909F">  repeated</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> Field</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> fields</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> =</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> 1;</span></span>
<span class="line"><span style="--shiki-light:#C11027;--shiki-dark:#FF909F">  uint64</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> rows_affected</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> =</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> 2;</span></span>
<span class="line"><span style="--shiki-light:#C11027;--shiki-dark:#FF909F">  uint64</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> insert_id</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> =</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> 3;</span></span>
<span class="line"><span style="--shiki-light:#C11027;--shiki-dark:#FF909F">  repeated</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> Row</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> rows</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> =</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> 4;</span></span>
<span class="line"><span style="--shiki-light:#C11027;--shiki-dark:#FF909F">  string</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> info</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> =</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> 6;</span></span>
<span class="line"><span style="--shiki-light:#C11027;--shiki-dark:#FF909F">  string</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> session_state_changes</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> =</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> 7;</span></span>
<span class="line"><span style="--shiki-light:#C11027;--shiki-dark:#FF909F">  bool</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> insert_id_changed</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> =</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> 8;</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">}</span></span>
<span class="line"></span>
<span class="line"><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">message Row </span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">{</span></span>
<span class="line"><span style="--shiki-light:#818181;--shiki-dark:#A1A1A1">  // -1 means NULL.</span></span>
<span class="line"><span style="--shiki-light:#C11027;--shiki-dark:#FF909F">  repeated</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> sint64</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> lengths</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> =</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> 1;</span></span>
<span class="line"></span>
<span class="line"><span style="--shiki-light:#818181;--shiki-dark:#A1A1A1">  // All non-NULL values concatenated together.</span></span>
<span class="line"><span style="--shiki-light:#C11027;--shiki-dark:#FF909F">  bytes</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> values</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> =</span><span style="--shiki-light:#C11027;--shiki-dark:#FF909F"> 2;</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">}</span></span>
<span class="line"></span></code></pre></div></div><p>This is a pretty compact protobuf representation. <code>lengths</code> tells us where the values are in the shared <code>values</code> byte string, so the protobuf doesn&#x27;t need a separate allocation for every value. The query engine can&#x27;t use the protobuf rows directly though. At the RPC boundary, <a href="https://github.com/vitessio/vitess/blob/main/go/sqltypes/proto3.go"><code>proto3ToRows</code></a> converts all of them:</p><div class="code-block" data-language="go"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">func</span><span style="--shiki-light:#5E49AF;--shiki-dark:#B7A5FB"> proto3ToRows</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">(</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">fields</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> []</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">*querypb</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">.</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">Field</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> rows</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> []</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">*querypb</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">.</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">Row</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">)</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> [][]</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">Value</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> {</span></span>
<span class="line"><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">    result</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> :=</span><span style="--shiki-light:#5E49AF;--shiki-dark:#B7A5FB"> make</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">([][]</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">Value</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span><span style="--shiki-light:#5E49AF;--shiki-dark:#B7A5FB"> len</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">(</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">rows</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">))</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">    for</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> i</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> r</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> :=</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> range</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> rows</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> {</span></span>
<span class="line"><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">        result</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">[</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">i</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">]</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> =</span><span style="--shiki-light:#5E49AF;--shiki-dark:#B7A5FB"> MakeRowTrusted</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">(</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">fields</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> r</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">)</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">    }</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">    return</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> result</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">}</span></span>
<span class="line"></span></code></pre></div></div><p>And <a href="https://github.com/vitessio/vitess/blob/main/go/sqltypes/result.go"><code>MakeRowTrusted</code></a> walks every column in every row:</p><div class="code-block" data-language="go"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">func</span><span style="--shiki-light:#5E49AF;--shiki-dark:#B7A5FB"> MakeRowTrusted</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">(</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">fields</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> []</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">*querypb</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">.</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">Field</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> row</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> *querypb</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">.</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">Row</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">)</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> []</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">Value</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> {</span></span>
<span class="line"><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">    sqlRow</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> :=</span><span style="--shiki-light:#5E49AF;--shiki-dark:#B7A5FB"> make</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">([]</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">Value</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span><span style="--shiki-light:#5E49AF;--shiki-dark:#B7A5FB"> len</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">(</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">row</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">.</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">Lengths</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">))</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">    var</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> offset</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> int64</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">    for</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> i</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> length</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> :=</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> range</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> row</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">.</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">Lengths</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> {</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">        if</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> length</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> &#x3C;</span><span style="--shiki-light:#D92038;--shiki-dark:#FF7082"> 0</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> {</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">            continue</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">        }</span></span>
<span class="line"><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">        sqlRow</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">[</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">i</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">]</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> =</span><span style="--shiki-light:#5E49AF;--shiki-dark:#B7A5FB"> MakeTrusted</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">(</span></span>
<span class="line"><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">            fields</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">[</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">i</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">].</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">Type</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span></span>
<span class="line"><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">            row</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">.</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">Values</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">[</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">offset</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">:</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">offset</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">+</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">length</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">],</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">        )</span></span>
<span class="line"><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">        offset</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> +=</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> length</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">    }</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">    return</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> sqlRow</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">}</span></span>
<span class="line"></span></code></pre></div></div><p><code>MakeTrusted</code> doesn&#x27;t turn every integer into a Go integer. A <code>Value</code> can still point at the bytes in the protobuf row. What we do get is a slice for every row and a <code>Value</code> for every non-NULL column before the query engine can do anything with the result. Going back across an RPC boundary does the reverse. <a href="https://github.com/vitessio/vitess/blob/main/go/sqltypes/proto3.go"><code>RowToProto3Inplace</code></a> first walks all the values to build the lengths and then walks them again to concatenate their bytes.</p><p>The protobuf result sits between separate Vitess components, while the query engine works with <code>[][]Value</code>. Converting at the boundary gives the engine one consistent type to work with. The downside is that every result gets converted, even when the router never looks at a value.</p><p>We wanted Neki to perform better, and therefore do less work in such cases.</p><h2 id="keeping-the-postgresql-response"><a href="https://planetscale.com/blog/designing-neki-for-performance#keeping-the-postgresql-response">Keeping the PostgreSQL response</a></h2><p>Neki also uses protobuf between the router and the <a href="https://planetscale.com/blog/the-architecture-of-neki#sidecar">sidecar</a> that sits in front of each PostgreSQL instance, but the result protobuf looks very different. Our <code>ExecuteResponse</code> is mostly a byte string:</p><div class="code-block" data-language="protobuf"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span>message ExecuteResponse {</span></span>
<span class="line"><span>  bytes raw = 1;</span></span>
<span class="line"><span>  int64 conn_id = 2;</span></span>
<span class="line"><span>  ...</span></span>
<span class="line"><span>}</span></span>
<span class="line"><span></span></span></code></pre></div></div><p><code>raw</code> contains PostgreSQL response messages. A <code>DataRow</code> in there is already a valid PostgreSQL <code>DataRow</code> that we can send to the client. Of course we still have to decode the <code>ExecuteResponse</code> protobuf to get the <code>raw</code> byte slice. That still leaves us with one byte slice. What we avoid is a protobuf object for every row, another slice of lengths for that row and a value for every column.</p><p>That doesn&#x27;t mean the router ignores the response. <code>NewQueryResponse</code> walks the five-byte message headers, validates the lengths, handles <code>CommandComplete</code> and finds the region containing the <code>DataRow</code> and <code>NoticeResponse</code> messages. This is stored as one byte slice in <code>DataRows</code>. We only open it further if the query needs us to.</p><p>For the examples here, we&#x27;ll use an <code>orders</code> table sharded by <code>account_id</code>:</p><div class="code-block" data-language="sql"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">CREATE</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> TABLE</span><span style="--shiki-light:#5E49AF;--shiki-dark:#B7A5FB"> orders</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1"> (</span></span>
<span class="line"><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">    id uuid </span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">NOT NULL</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">,</span></span>
<span class="line"><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">    account_id </span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">bigint</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> NOT NULL</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">,</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">    status</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> text</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> NOT NULL</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">,</span></span>
<span class="line"><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">    created_at </span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">timestamptz</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> NOT NULL</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">,</span></span>
<span class="line"><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">    total </span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">numeric</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> NOT NULL</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">,</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">    PRIMARY KEY</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1"> (account_id, id)</span></span>
<span class="line"><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">);</span></span>
<span class="line"></span></code></pre></div></div><h2 id="a-result-we-dont-need-to-decode"><a href="https://planetscale.com/blog/designing-neki-for-performance#a-result-we-dont-need-to-decode">A result we don&#x27;t need to decode</a></h2><p>The simplest example is a point lookup:</p><div class="code-block" data-language="sql"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">SELECT</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1"> id, </span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">status</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">, total</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">FROM</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1"> orders</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">WHERE</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1"> account_id </span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">=</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1"> $</span><span style="--shiki-light:#D92038;--shiki-dark:#FF7082">1</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">  AND</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1"> id </span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">=</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1"> $</span><span style="--shiki-light:#D92038;--shiki-dark:#FF7082">2</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">;</span></span>
<span class="line"></span></code></pre></div></div><p>Because <code>account_id</code> is the sharding key, Neki needs the value in <code>$1</code> to pick the shard. It doesn&#x27;t need to understand <code>id</code>, <code>status</code> or <code>total</code> when they come back. Those values only need to make it from PostgreSQL to the client. We can use the same approach on the way into the router too.</p><h3 id="bind-parameters-are-rows-going-the-other-way"><a href="https://planetscale.com/blog/designing-neki-for-performance#bind-parameters-are-rows-going-the-other-way">Bind parameters are rows going the other way</a></h3><p>With PostgreSQL&#x27;s extended query protocol, <code>$1</code> and <code>$2</code> arrive in a <a href="https://www.postgresql.org/docs/current/protocol-message-formats.html"><code>Bind</code> message</a>. Each parameter is length-prefixed as a column in a <code>DataRow</code>:</p><div class="code-block" data-language="text"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span>NULL:     Int32(-1)</span></span>
<span class="line"><span>non-NULL: Int32(length), followed by value bytes</span></span>
<span class="line"><span></span></span></code></pre></div></div><p>The difference is where the format comes from. <code>Bind</code> includes format codes for its parameters, while the formats for <code>DataRow</code> columns come from <code>RowDescription</code>. The <a href="https://www.postgresql.org/docs/current/protocol-message-formats.html">PostgreSQL protocol message documentation</a> has all the details if you want to know all the fun little bits about the protocol.</p><p>Neki keeps the original <code>Bind</code> message and a cache for the parameters it has decoded. For our point lookup, the router scans the parameter frames, decodes the bigint in <code>$1</code> and caches it. We don&#x27;t need <code>$2</code> for routing. When the query is sent to the shard, Neki writes the original parameter frames directly as long as the client encoding hasn&#x27;t changed.</p><p>Keeping the original frames also helps when we rewrite a query. A rewritten query might use only some parameters, put them in a different order or use the same one multiple times. A mapping like <code>[1, 0, 1]</code> copies the parameter frames into a new <code>Bind</code>. We can use the same approach when adding parameters to the existing list.</p><p><a href="https://en.wikipedia.org/wiki/Nested_loop_join">Nested loop joins</a> have a similar case. A column from a row on the left becomes a parameter for a query on the right. Neki copies the complete length-prefixed column frame from the <code>DataRow</code> into the new <code>Bind</code>. We only turn the join key into a typed value if we also need it for routing or evaluation.</p><h3 id="text-stays-text-and-binary-stays-binary"><a href="https://planetscale.com/blog/designing-neki-for-performance#text-stays-text-and-binary-stays-binary">Text stays text and binary stays binary</a></h3><p>There is one more wrinkle: PostgreSQL values can be sent as text or binary. The client uses <code>Bind</code> to tell PostgreSQL which formats it used for the parameters and wants for the result columns. Instead of up-front conversions like Vitess would require, Neki keeps values in the original formats.</p><p>When a query selects <code>id</code> and <code>account_id</code> but orders by <code>created_at</code> without selecting it, <code>id</code> and <code>account_id</code> use the formats requested by the client. The extra <code>created_at</code> column uses binary because only Neki needs it. The client will never see those column values.</p><p>If Neki needs to decode a value, <code>RowDescription</code> tells it whether to use the text or binary decoder. If it doesn&#x27;t, the bytes stay untouched. When Neki produces a new value, it uses the format requested by the client.</p><p>Conversion is still needed if <code>client_encoding</code> changes between <code>Bind</code> and <code>Execute</code>. Affected text parameters are recoded before they are sent to PostgreSQL. The other parameters stay as they are.</p><p>Now let&#x27;s go back to the result from the point lookup. <code>DataRows</code> can hold one raw byte slice, a slice of rows that point into those bytes or a slice of pointers used to select and reorder those rows. It only creates the next representation when a query needs it.</p><p>In this case, Neki writes the raw bytes straight to the client.</p><p>No <code>DataRow</code> structs and no columns! Just the PostgreSQL messages that we already had in the correct Postgres wire format. This also works for cross-shard queries. In the query below, <code>status</code> isn&#x27;t the sharding key so it will have to get passed along to every shard to collect results:</p><div class="code-block" data-language="sql"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">SELECT</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1"> id, account_id, </span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">status</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">FROM</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1"> orders</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">WHERE</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> status</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> =</span><span style="--shiki-light:#13862E;--shiki-dark:#75DB8C"> 'pending'</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">;</span></span>
<span class="line"></span></code></pre></div></div><p>There is no global order and no sums / averages to calculate across the results. This means we can optimize. After sending the scatter queries, Neki streams response chunks from each shard, combines the separate <code>CommandComplete</code> messages with <code>Collapse</code>, and <code>DataRow</code>s can be passed along unmodified. It&#x27;s a &quot;complex&quot; distributed query, but there is nothing in the rows we need to decode.</p><h2 id="adding-limit"><a href="https://planetscale.com/blog/designing-neki-for-performance#adding-limit">Adding <code>LIMIT</code></a></h2><p>Now let&#x27;s add a limit:</p><div class="code-block" data-language="sql"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">SELECT</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1"> id, account_id, </span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">status</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">FROM</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1"> orders</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">WHERE</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> status</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> =</span><span style="--shiki-light:#13862E;--shiki-dark:#75DB8C"> 'pending'</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">LIMIT</span><span style="--shiki-light:#D92038;--shiki-dark:#FF7082"> 100</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">;</span></span>
<span class="line"></span></code></pre></div></div><p>Now we need to know when we&#x27;ve sent 100 rows, which means the response cannot be an opaque byte slice. <code>Limit</code> calls <code>DataRows.Len()</code>, and on the first call we walk the raw response and count the <code>DataRow</code> messages so the row slice can be allocated once. In a second pass, we create the <code>DataRow</code> wrappers which all point into the original response buffer.</p><p>Once we have the row boundaries, <code>Limit</code> builds a pointer slice for the requested window:</p><div class="code-block" data-language="go"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">ptrs</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> :=</span><span style="--shiki-light:#5E49AF;--shiki-dark:#B7A5FB"> make</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">([]</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">*runtime</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">.</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">DataRow</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> n</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">)</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">for</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> i</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> :=</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> range</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> n</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> {</span></span>
<span class="line"><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">    ptrs</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">[</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">i</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">]</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> =</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> response</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">.</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">Rows</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">.</span><span style="--shiki-light:#5E49AF;--shiki-dark:#B7A5FB">Row</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">(</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">int</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">(</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">startIdx</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">)</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> +</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> int</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">(</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">i</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">))</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">}</span></span>
<span class="line"></span>
<span class="line"><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">response</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">.</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">Rows</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> =</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> runtime</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">.</span><span style="--shiki-light:#5E49AF;--shiki-dark:#B7A5FB">NewDataRowsFromPtrsWithNotices</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">(</span></span>
<span class="line"><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">    ptrs</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span></span>
<span class="line"><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">    notices</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">)</span></span>
<span class="line"></span></code></pre></div></div><p><code>ptrs</code> is the third representation in <code>DataRows</code>. It lets us take a subset of the rows or put them in a different order without moving row messages.</p><p>For this query Neki knows where every row starts and ends. What it <em>doesn&#x27;t</em> know is the value of a single <code>id</code>, <code>account_id</code> or <code>status</code> column. Counting rows doesn&#x27;t require that... but what if it did?</p><h2 id="sorting-means-decoding-the-sort-key"><a href="https://planetscale.com/blog/designing-neki-for-performance#sorting-means-decoding-the-sort-key">Sorting means decoding the sort key</a></h2><p>For a pending orders page, we&#x27;d probably want a stable sorting:</p><div class="code-block" data-language="sql"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">SELECT</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1"> id, account_id, created_at</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">FROM</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1"> orders</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">WHERE</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> status</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> =</span><span style="--shiki-light:#13862E;--shiki-dark:#75DB8C"> 'pending'</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">ORDER BY</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1"> created_at </span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">DESC</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">LIMIT</span><span style="--shiki-light:#D92038;--shiki-dark:#FF7082"> 100</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">;</span></span>
<span class="line"></span></code></pre></div></div><p>Each shard sorts its subset of results (within Postgres), but the router has to merge those distinct result sets into a global order. Now we finally have to decode a column. First we need the rows, the same as for <code>LIMIT</code>, and then we need to find <code>created_at</code> inside each row.</p><p>At the protocol level, a <code>DataRow</code> keeps the complete PostgreSQL message and a view of the bytes containing its columns. The column bytes start after the five-byte message header and the two-byte column count. Each column has a four-byte length followed by the value bytes. A length of <code>-1</code> means <code>NULL</code>.</p><p>To get to the third column, we have to read the lengths of the first two columns and skip their payloads. Reading the lengths of these columns doesn&#x27;t decode the values. We now know where <code>id</code> and <code>account_id</code> are, but the bytes still have no meaning to the router. With the offsets, we can jump to the correct bytes to grab <code>created_at</code> for each row.</p><p>These timestamps are cached because a row will normally be compared more than once while merging results. At this point all rows have been exposed and we&#x27;ve looked at their column framing. The actual values look like this though:</p><div class="code-block" data-language="text"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span>id          frame located, payload not decoded</span></span>
<span class="line"><span>account_id  frame located, payload not decoded</span></span>
<span class="line"><span>created_at  frame located, payload decoded and cached</span></span>
<span class="line"><span></span></span></code></pre></div></div><p>The merge produces another <code>DataRows</code> with pointers to the original rows, now in the right order. Sorting rows doesn&#x27;t require copying the rows.</p><iframe src="https://planetscale.com/blog/designing-neki-for-performance/rows-as-pointers/iframe" title="Sorting DataRows by rearranging pointers while the response buffer stays unchanged" loading="lazy"></iframe><h2 id="dropping-a-column-without-decoding"><a href="https://planetscale.com/blog/designing-neki-for-performance#dropping-a-column-without-decoding">Dropping a column without decoding</a></h2><p>A small change can have a big impact on what work we can and cannot skip. How about we don&#x27;t select <code>created_at</code>:</p><div class="code-block" data-language="sql"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">SELECT</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1"> id, account_id</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">FROM</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1"> orders</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">WHERE</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> status</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> =</span><span style="--shiki-light:#13862E;--shiki-dark:#75DB8C"> 'pending'</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">ORDER BY</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1"> created_at </span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">DESC</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">LIMIT</span><span style="--shiki-light:#D92038;--shiki-dark:#FF7082"> 100</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">;</span></span>
<span class="line"></span></code></pre></div></div><p>Ordering by a column without returning it is a very normal query, but it does give the router one extra problem. The shards have to return <code>created_at</code> because Neki needs it for the merge. Before we send the rows to the client, that extra column has to be removed.</p><p>Recall from the last section that by the end we reached the point where <code>created_at</code> had been decoded, but <code>id</code> and <code>account_id</code> were still only protocol frames. For this one, there&#x27;s more to do.</p><p>The naive implementation would read <code>id</code> and <code>account_id</code> as values, build a new row and serialize them again. That&#x27;s a lot of work to remove a few bytes from the end of a message.</p><p>Instead, <code>SimpleProjection</code> stores the projection as runs of adjacent input columns. Each run contains the first and last column, so <code>{0,2}</code> is one run covering columns 0, 1 and 2. This lets <code>ProjectInto</code> copy all three column frames as one byte range. Skipping, reordering or duplicating columns creates more runs, stored in output order:</p><div class="code-block" data-language="text"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span>stored runs          byte ranges copied</span></span>
<span class="line"><span>[{0,2}]              columns 0–2 in one copy</span></span>
<span class="line"><span>[{0,2}, {4,6}]       columns 0–2, then 4–6 in two copies</span></span>
<span class="line"><span>[{3,3}, {0,2}]       column 3, then 0–2 in two copies</span></span>
<span class="line"><span>[{0,0}, {0,0}]       column 0 twice in two copies</span></span>
<span class="line"><span></span></span></code></pre></div></div><p>Our query needs only one run, <code>{0,1}</code>. At execution time we find the byte range containing both length-prefixed columns, write a new <code>DataRow</code> header with a column count of two and append both columns at once.</p><p>The byte-backed projection does one append per run. <code>Values</code> is the row&#x27;s view of the column bytes, and <code>offsets</code> contains the frame boundaries found while scanning it:</p><div class="code-block" data-language="go"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">for</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> _</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> r</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> :=</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> range</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600"> runs</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> {</span></span>
<span class="line"><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">    dst</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> =</span><span style="--shiki-light:#5E49AF;--shiki-dark:#B7A5FB"> append</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">(</span></span>
<span class="line"><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">        dst</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span></span>
<span class="line"><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">        dr</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">.</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">Values</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">[</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">offsets</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">[</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">r</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">.</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">Start</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">]:</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">offsets</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">[</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">r</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">.</span><span style="--shiki-light:#A78103;--shiki-dark:#F2B600">End</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">+</span><span style="--shiki-light:#D92038;--shiki-dark:#FF7082">1</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">]]</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">...</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">    )</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">}</span></span>
<span class="line"></span></code></pre></div></div><iframe src="https://planetscale.com/blog/designing-neki-for-performance/data-row-projection/iframe" title="Projecting a PostgreSQL DataRow by copying complete column frames into a shared output buffer" loading="lazy"></iframe><p>This isn&#x27;t zero-copy because we are creating a different PostgreSQL message. The new header and the columns have to go somewhere. We do copy the exact <code>id</code> and <code>account_id</code> frames though, still saving a good amount of work through careful optimization.</p><p>Normally we&#x27;re projecting a complete response batch, not one random row. Neki appends all the new rows to one shared wire buffer. The finished rows are then bounded views into that buffer, so there isn&#x27;t a separate backing buffer for every output row.</p><p>The slightly funny part is that we decoded <code>created_at</code>, which the client didn&#x27;t ask for, and didn&#x27;t decode <code>id</code> or <code>account_id</code>, which it did ask for. That&#x27;s exactly the work this query required. In Neki, we take every opportunity to skip unnecessary work.</p><h2 id="when-we-really-need-values"><a href="https://planetscale.com/blog/designing-neki-for-performance#when-we-really-need-values">When we really need values</a></h2><p>Of course some queries do require the router to understand and produce values. A cross-shard aggregate is a good example:</p><div class="code-block" data-language="sql"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">SELECT</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> status</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">, </span><span style="--shiki-light:#0B6EC5;--shiki-dark:#73C7F9">count</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">(</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">*</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">)</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">FROM</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1"> orders</span></span>
<span class="line"><span style="--shiki-light:#F35815;--shiki-dark:#F35815">GROUP BY</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815"> status</span><span style="--shiki-light:#2B2B2B;--shiki-dark:#E1E1E1">;</span></span>
<span class="line"></span></code></pre></div></div><p>The same <code>status</code> can exist on many shards, so we can&#x27;t rely on PostgreSQL to do the full <code>GROUP BY</code>. The Neki router must handle it.</p><p>We need the group key and the partial counts as values. There isn&#x27;t a useful byte-level trick for grouping equal values and adding the counts. The final count is also a new value produced by the router, so there are no original PostgreSQL bytes to copy.</p><p>For a row like this, we cannot get away with just passing along bytes from Postgres to clients.</p><p>When a results row from this query is sent to the client, Neki serializes those values into a new PostgreSQL <code>DataRow</code> in the format the client requested. This query MUST go through every layer:</p><div class="code-block" data-language="text"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span>response messages</span></span>
<span class="line"><span>    -> result batches</span></span>
<span class="line"><span>        -> rows</span></span>
<span class="line"><span>            -> column frames</span></span>
<span class="line"><span>                -> typed values</span></span>
<span class="line"><span>                    -> newly computed values</span></span>
<span class="line"><span></span></span></code></pre></div></div><h2 id="bytes-and-values-at-the-same-time"><a href="https://planetscale.com/blog/designing-neki-for-performance#bytes-and-values-at-the-same-time">Bytes and values at the same time</a></h2><p>Neki doesn&#x27;t have one internal row representation. A row received from PostgreSQL starts wire-backed, while a row produced by an aggregate can be completely value-backed. The sorted rows from a few sections ago are a mix of the two: they keep the original message and have a cached <code>created_at</code> value.</p><div class="code-block" data-language="text"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span>Original: complete PostgreSQL DataRow</span></span>
<span class="line"><span></span></span>
<span class="line"><span>values[0]: no decoded value</span></span>
<span class="line"><span>values[1]: no decoded value</span></span>
<span class="line"><span>values[2]: decoded created_at</span></span>
<span class="line"><span></span></span></code></pre></div></div><p>The original message is still available for forwarding or projection, while the cache avoids decoding <code>created_at</code> again every time the row is compared.</p><p>Cached values survive projection too. If a projection keeps or moves a decoded column, Neki copies the original frame and remaps the cached value to its new position. We took the performance hit in decoding the timestamp because the query needed it, but we want to make sure we don&#x27;t decode or serialize it again.</p><p>For PostgreSQL records this can also be necessary for correctness. A record can have a transient <code>typmod</code> describing it, which isn&#x27;t always recoverable from the wire bytes. Raw projection won&#x27;t allocate a cache in the case where none of the projected columns have decoded values.</p><h2 id="using-this-trick-elsewhere"><a href="https://planetscale.com/blog/designing-neki-for-performance#using-this-trick-elsewhere">Using this trick elsewhere</a></h2><p>This way of working with protocol frames isn&#x27;t limited to sorting and projection. For joins, we decode the keys needed to match rows. The output can still be assembled from contiguous runs of columns from the left and right rows. We avoid doing the extra work of producing values whenever we can!</p><p>When we need to spill rows to disk, we also keep things in the self-framing PostgreSQL <code>DataRow</code> format. We can write and read from disk with minimal additional decoding overhead.</p><p>Keeping bind parameters in their original length-prefixed representation is not just about performance either. Parsing and serializing a value isn&#x27;t guaranteed to give us identical bytes. A floating point NaN payload, for example, can survive PostgreSQL&#x27;s receive function but change when it is sent again.</p><p>PostgreSQL extension types are another useful case. The router might have no idea how to evaluate a value from an extension, but it can still pass the protocol bytes through.</p><h2 id="keeping-the-layers-composable"><a href="https://planetscale.com/blog/designing-neki-for-performance#keeping-the-layers-composable">Keeping the layers composable</a></h2><p>The nice part of this model is that each representation builds on the previous one. <code>DataRows</code> can start with raw response bytes, expose those bytes as a row slice and then add a pointer slice for a subset or a different order. An individual row can keep its original PostgreSQL message while also caching the values that have been decoded. Going one layer deeper for one part of a query doesn&#x27;t force all columns / values to do so.</p><p>Of course that doesn&#x27;t make the complexity disappear. Byte-level projection still has to calculate the right offsets, write a new message header and copy the right column frames in the right order. The key thing for Neki&#x27;s performance though, is that it&#x27;s all contained in the row projection and batch builder.</p><p>It also gives us a small surface we can test directly. The projection tests construct PostgreSQL messages byte by byte and cover reordering, <code>NULL</code>, empty strings, empty <code>bytea</code>, duplicate columns and the protocol-backed path.</p><p>There are a few invariants we have to maintain for that containment to work. Shared response buffers have to remain alive as long as a row still points into them. We use three-index slices because an append through one row must not overwrite the next PostgreSQL message in the same buffer. Two consumers replaying the same buffered row need their own row wrapper and value cache, while the immutable protocol bytes can still be shared.</p><p>Memory accounting also has to know that a row can grow. It starts out retaining the wire bytes, but every string, numeric or record added to the cache uses more memory. And then it all has to work with <code>NULL</code>, text and binary formats, client encodings, arrays, domains, records and user-defined types. If moving the bytes around changes the result, we&#x27;ve built a very fast bug 😉.</p><h2 id="nothing-is-still-the-fastest"><a href="https://planetscale.com/blog/designing-neki-for-performance#nothing-is-still-the-fastest">Nothing is still the fastest</a></h2><p>Neki does a lot of real work. It routes queries and sometimes has to merge, compare, group or compute values across shards, but it doesn&#x27;t have to do all of that for every column in every query. A point lookup can keep the result as PostgreSQL messages. <code>LIMIT</code> needs row boundaries. Sorting needs the sort keys. Projection can move existing column frames around. An aggregate generates newly computed values because there is no earlier layer where it can stop.</p><p>For every query the router tries to do the least possible work. The best way to make software fast is to avoid work at all costs.</p>]]></content>
    <summary><![CDATA[Nothing is as fast as not doing anything. How Neki keeps great performance by only decoding the parts of a PostgreSQL result the router actually needs.]]></summary>
  </entry>
  <entry>
    <title>Handling hot shards</title>
    <link href="https://planetscale.com/blog/hot-shards-hotter-tenants"/>
    <id>https://planetscale.com/blog/hot-shards-hotter-tenants</id>
    <published>2026-09-28T00:00:00.000Z</published>
    <updated>2026-09-28T00:00:00.000Z</updated>
    <author>
      <name>Simeon Griggs</name>
    </author>
    <category term="engineering"/>
    <category term="vitess"/>
    <category term="neki"/>
    <category term="postgres"/>
    <content type="html"><![CDATA[<p>Since the launch of Neki we&#x27;ve talked a lot about sharding with basic examples to demonstrate how Neki splits a table&#x27;s rows evenly across shards. Neki&#x27;s router reads your <a href="https://planetscale.com/blog/what-is-a-data-topology">data topology</a> to handle the placement of writes and to find the correct shard for reads.</p><p>But life in production is never so simple.</p><p>Imagine your application&#x27;s Neki database is sharding on a <code>tenant_id</code> column. Makes sense. You want a nice even distribution of tenants across shards. But your app takes off, congratulations! Now, some tenants are hitting their shard at a greater size or volume than most. New product opportunities emerge that require cross-tenant queries.</p><p>Suddenly an even distribution of <em>tenants</em> is less useful than an even distribution of <em>data</em>.</p><p>You probably just have the wrong shard key, at least for some of your data. No problem, Neki gives you the tools to mitigate increased pressure on shards, and adapt your resharding strategy, without downtime.</p><h2 id="a-story-of-resharding-success"><a href="https://planetscale.com/blog/hot-shards-hotter-tenants#a-story-of-resharding-success">A story of resharding success</a></h2><p>While Neki is new, sharding isn&#x27;t. Neki is built by the maintainers of Vitess: a proven, scalable and flexible solution that has a great history of solving these exact problems.</p><p>Slack has published multiple articles (<a href="https://planetscale.com/blog/hot-shards-hotter-tenants#footnotes">1</a>, <a href="https://planetscale.com/blog/hot-shards-hotter-tenants#footnotes">2</a>) and talks (<a href="https://planetscale.com/blog/hot-shards-hotter-tenants#footnotes">3</a>) on how they had to modify their approach to sharding as product demand and requirements changed over time thanks to Slack&#x27;s rapid rise in popularity.</p><p>Their original tidy and <em>obvious</em> way to shard <strong>message</strong> and <strong>channel</strong> data was by the ID of the <strong>workspace</strong> to which they belonged. The logic of which <strong>workspace</strong> belonged to which <strong>shard</strong> was maintained in a cluster dedicated to sharding metadata.</p><p>The assumption was reasonable, that no single customer would ever outgrow the biggest database. But then a workspace of 10s of 1000s of users lands. Then 100s of 1000s. Vertical scaling and isolation bought time, but not enough.</p><p>Over time this became problematic.</p><iframe src="https://planetscale.com/blog/hot-shards-hotter-tenants/iframe#workspace-groups" title="Messages and channels grouped by workspace across two shards" loading="lazy"></iframe><p><em>With per-workspace sharding, a single hot tenant&#x27;s messages table quickly overwhelms the shard</em></p><p>As the product got more successful, some workspaces were far more demanding than others. Workspaces for large enterprises could contain over 100,000 users, which ballooned the initial payload the client application needed. Some <strong>workspaces&#x27; messages</strong> tables were getting too large for any one shard. Cross-workspace messaging became a requirement. A new enterprise grid feature needed to organize multiple workspaces under a single enterprise organization. All of this was being made complicated by the current &quot;shard by workspace&quot; strategy.</p><p>Their solution involved Vitess, a sharding solution for MySQL, to simplify resharding, starting with sharding <strong>messages</strong> by <strong>channel</strong> instead of <strong>workspace</strong>.</p><p>Not every table changed. Each table was explicitly sharded by the column that made the most sense for it: user ID, channel ID, <em>or</em> workspace ID. This created a simpler path to spreading out data load across shards and enabling cross-workspace communication.</p><iframe src="https://planetscale.com/blog/hot-shards-hotter-tenants/iframe#spread" title="Channels stay on two workspace shards. Messages from every workspace land on two message shards." loading="lazy"></iframe><p><em>Sharding the messages table by channel across shards smoothed out load and unlocked new product opportunities</em></p><h3 id="explicit-vs-automatic-sharding"><a href="https://planetscale.com/blog/hot-shards-hotter-tenants#explicit-vs-automatic-sharding">Explicit vs automatic sharding</a></h3><p>Among other benefits, shard allocation was no longer hidden in application logic and a separate metadata cluster. It was defined explicitly in Vitess and enforced by VTGate. Neki&#x27;s equivalent is the data topology: a declarative configuration that agents and humans can read to reason about where data is written and where it can be read from. You define the columns on which specific tables are sharded and the range of values each shard receives.</p><p>This is in contrast to automatic sharding solutions, where the database decides placement for you, which can result in unexpected or unpredictable placement of rows.</p><p>Agents love declarative configuration like a data topology because it&#x27;s foolproof to reason about exactly where data will land and why. Which tables are sharded, which key they&#x27;re sharded by, and which shards sharded rows are sharded to are all determined by the data topology.</p><p>At any time, you can add shards and change sharding strategies. After which, <a href="https://planetscale.com/docs/neki/data-migration#reshard-existing-tables">Reshard</a> copies existing rows to new shards as required and streams ongoing writes while the source keeps serving. When you switch traffic, Neki moves reads and writes to the new placement without taking the application offline.</p><h2 id="solving-resharding-with-neki"><a href="https://planetscale.com/blog/hot-shards-hotter-tenants#solving-resharding-with-neki">Solving resharding with Neki</a></h2><p>Should you suffer from the same success, and have already migrated to Neki, you&#x27;re in a great position as it gives you the tools to mitigate increased demand and/or adjust your sharding strategy with minimal effort and disruption.</p><p>Here&#x27;s three ways to handle increased demand and requirements. The first two buy you time, the last one is the best long-term solution.</p><h3 id="fix-1-scale-up"><a href="https://planetscale.com/blog/hot-shards-hotter-tenants#fix-1-scale-up">Fix 1: Scale up</a></h3><p>If increased demand has your databases hitting their limits, the easy answer is just &quot;add more resources.&quot; You could do that and stop here.</p><p>Each shard in a Neki database is a distinct Postgres cluster with its own resources. Configuration profiles can be distinct or shared across shards. You can temporarily solve your large tenant problem by assigning its shard a unique profile, vertically scaling it, and going about your business.</p><p>On Vitess, <a href="https://planetscale.com/docs/vitess/cluster-configuration/per-shard-sizing">per-shard sizing</a> does the same job by giving a hot shard a larger cluster size than the rest of its keyspace.</p><h3 id="fix-2-isolate-large-tenants"><a href="https://planetscale.com/blog/hot-shards-hotter-tenants#fix-2-isolate-large-tenants">Fix 2: Isolate large tenants</a></h3><p>Additionally, if your larger tenants are causing issues for their neighbours, you can isolate the range of tenants on any one shard.</p><p>Here&#x27;s a visual representation of distributing rows across shards. Note that <code>xxhash</code> doesn&#x27;t create a perfectly even balance of this small dataset, but would be relatively even over 1000s or more rows.</p><iframe src="https://planetscale.com/blog/hot-shards-hotter-tenants/iframe" title="Interactive: hash-range shards with a whale tenant isolated into its own key range" loading="lazy"></iframe><p>Since you&#x27;re in control, distribution can be as broad or fine grained as you like. In a simplified sharding example, an even distribution of hashed IDs across two shards would look like this:</p><div class="code-block" data-language="json"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">{</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">  "</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">key_ranges</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">:</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> [</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">    {</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> "</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">shard_uid</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">:</span><span style="--shiki-light:#13862E;--shiki-dark:#75DB8C"> "shard-a"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> "</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">end</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">:</span><span style="--shiki-light:#13862E;--shiki-dark:#75DB8C"> "80"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> },</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">    {</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> "</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">shard_uid</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">:</span><span style="--shiki-light:#13862E;--shiki-dark:#75DB8C"> "shard-b"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> "</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">start</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">:</span><span style="--shiki-light:#13862E;--shiki-dark:#75DB8C"> "80"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> }</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">  ]</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">}</span></span>
<span class="line"></span></code></pre></div></div><p>The start and end ranges in the code example above are only matching the first two characters of a hashed ID. You can go much finer and create a tighter range around the whale&#x27;s <code>tenant_id</code>.</p><p>Isolating the whale&#x27;s data will require resharding all tenants&#x27; data. Reshard copies rows onto new shards, so we cannot re-use the original source shards <code>shard-a</code> and <code>shard-b</code>. With three new shards created, the new layout below describes an updated placement to isolate the hot tenant&#x27;s data.</p><div class="code-block" data-language="json"><div class="max-w-full min-w-0"><pre class="shiki shiki-themes planetscale-light planetscale-dark" style="--shiki-light:#2b2b2b;--shiki-dark:#e1e1e1;--shiki-light-bg:#ebebeb;--shiki-dark-bg:#1a1a1a" tabindex="0"><code><span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">{</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">  "</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">key_ranges</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">:</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> [</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">    {</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> "</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">shard_uid</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">:</span><span style="--shiki-light:#13862E;--shiki-dark:#75DB8C"> "shard-c"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> "</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">end</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">:</span><span style="--shiki-light:#13862E;--shiki-dark:#75DB8C"> "80a3f1"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> },</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">    {</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> "</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">shard_uid</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">:</span><span style="--shiki-light:#13862E;--shiki-dark:#75DB8C"> "whale"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> "</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">start</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">:</span><span style="--shiki-light:#13862E;--shiki-dark:#75DB8C"> "80a3f1"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> "</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">end</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">:</span><span style="--shiki-light:#13862E;--shiki-dark:#75DB8C"> "80a3f2"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> },</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">    {</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> "</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">shard_uid</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">:</span><span style="--shiki-light:#13862E;--shiki-dark:#75DB8C"> "shard-d"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">,</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> "</span><span style="--shiki-light:#F35815;--shiki-dark:#F35815">start</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">:</span><span style="--shiki-light:#13862E;--shiki-dark:#75DB8C"> "80a3f2"</span><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1"> }</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">  ]</span></span>
<span class="line"><span style="--shiki-light:#616161;--shiki-dark:#C1C1C1">}</span></span>
<span class="line"></span></code></pre></div></div><p>However, you&#x27;ve now created an environment where one very large tenant can have one extremely large table. A table so large it too would benefit from being sharded. If CPU demands don&#x27;t get you, storage will. It may be time to make some structural sharding changes.</p><h3 id="fix-3-reshard-some-tables"><a href="https://planetscale.com/blog/hot-shards-hotter-tenants#fix-3-reshard-some-tables">Fix 3: Reshard some tables</a></h3><p>Vertical scaling and isolation of a tenant will only get you so far, but neither of the previous two fixes solves the root cause of your problem. Yesterday&#x27;s sharding strategy is unsuitable for today&#x27;s requirements.</p><p>Changing sharding strategy doesn&#x27;t mean sharding or resharding everything. Unless you&#x27;re Meta or Google you probably don&#x27;t need to shard your users table.</p><p>Investigate your application&#x27;s access patterns and query shapes to work out what other dimensions data can be sharded by. Look for tables which are regularly joined by a common column key, reshard so they are kept together.</p><p>Back to Slack&#x27;s example, messages were always queried by channel, never by workspace, and channel ID was already part of the messages table&#x27;s primary key. The right shard key had been there all along. Sharding messages by channel ID made fetching a channel and its messages a single-shard query, even when those messages were authored by users in different workspaces.</p><iframe src="https://planetscale.com/blog/hot-shards-hotter-tenants/iframe#by-channel" title="Before: messages, channels, and users share two workspace shards. After: messages spread onto two new shards, and channels and users stay." loading="lazy"></iframe><p>Cross-channel queries for messages, which would now be cross-shard queries, were limited to administrative or batch operations, not the critical path. This change cooled off hot spots and gave the team a lot more runway in terms of CPU and storage. Meanwhile, keeping the users table together was critical, as searching for &quot;all users in this workspace&quot; was a common access path.</p><p>While resharding isn&#x27;t something you&#x27;ll want to do often, it&#x27;s simpler once you are already within a sharded database. During resharding, Neki will continue to serve queries to existing data until the operation is complete.</p><h2 id="conclusion"><a href="https://planetscale.com/blog/hot-shards-hotter-tenants#conclusion">Conclusion</a></h2><p>Landing big customers and growing your product are good problems to have, but how much stress it causes you depends on the foundation you already have in place. With Neki as that foundation, you are choosing something you and your agents can easily understand, change, and adapt to, no matter which dimension your data grows by.</p><p>The longer you wait, the more tables outgrow their original shard key. What could have been one change becomes several at once. Don&#x27;t wait for a perfect future state. Shard the table that hurts today and address the rest as they need it.</p><p>Shard what hurts now.</p><h2 id="footnotes"><a href="https://planetscale.com/blog/hot-shards-hotter-tenants#footnotes">Footnotes</a></h2><ol><li><a href="https://slack.engineering/scaling-datastores-at-slack-with-vitess/">Scaling Datastores at Slack with Vitess</a></li><li><a href="https://slack.engineering/unified-grid-how-we-re-architected-slack-for-our-largest-customers/">Unified Grid: How We Re-Architected Slack for Our Largest Customers</a></li><li><a href="https://www.infoq.com/presentations/slack-scalability-2018/">Scaling Slack</a></li></ol>]]></content>
    <summary><![CDATA[What makes a good sharding strategy today might not work so well tomorrow. What happens when you have one tenant hitting your database orders of magnitude more than any other? Or product managers knocking down your door with new requirements? If you're already on Neki, fortunately these are issues we can solve.]]></summary>
  </entry>
  <entry>
    <title>The architecture of Neki</title>
    <link href="https://planetscale.com/blog/the-architecture-of-neki"/>
    <id>https://planetscale.com/blog/the-architecture-of-neki</id>
    <published>2026-09-18T00:00:00.000Z</published>
    <updated>2026-09-18T00:00:00.000Z</updated>
    <author>
      <name>Harshit Gangal</name>
    </author>
    <category term="engineering"/>
    <category term="neki"/>
    <content type="html"><![CDATA[<p>Meet Neki: sharding for Postgres. Neki allows applications to connect to massive, sharded databases over a single connection string. This post takes apart the architecture from the bottom up, one piece at a time, starting with what&#x27;s underneath all of it.</p><h2 id="real-postgres"><a href="https://planetscale.com/blog/the-architecture-of-neki#real-postgres">Real Postgres</a></h2><p>Neki is built as a sharding and scaling solution for real Postgres. It&#x27;s not a fork, nor a wire-compatible reimplementation, nor a MySQL sharding idea wearing a Postgres label. Neki uses ordinary PostgreSQL instances that store rows in Postgres data pages using MVCC, carry out transactions, and work as you would expect with <code>psql</code> and other Postgres drivers. Neki builds around those instances to let you shard them, scale them, and manage them as one database.</p><p>Let&#x27;s take a look:</p><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/neki-cluster-architecture-DVbFbIVf.svg?auto=compress%2Cformat"><source media="(prefers-color-scheme: dark)" srcSet="https://planetscale-images.imgix.net/assets/neki-cluster-architecture-darkmode-DZFLB57F.svg?auto=compress%2Cformat"><img alt="The full Neki cluster: an application talking to the Router, two shards each with a primary and a replica running Sidecar, Postgres, and Replicator, PostgresManager controlling each Postgres instance, Admin and etcd forming the control plane, and an Operator provisioning every pod." src="https://planetscale-images.imgix.net/assets/neki-cluster-architecture-DVbFbIVf.svg?auto=compress%2Cformat" width="1504" height="1058" loading="lazy"></picture></p><h2 id="postgresmanager"><a href="https://planetscale.com/blog/the-architecture-of-neki#postgresmanager">PostgresManager</a></h2><p>Using vanilla Postgres means Neki needs a way to run and manage each instance. That includes starting and stopping Postgres, owning its data directory, and configuring replication so a new instance can join a shard. <strong>PostgresManager</strong> handles this coordination, running as the first process in the Postgres container and managing the <code>postgres</code> process directly.</p><h2 id="sidecar"><a href="https://planetscale.com/blog/the-architecture-of-neki#sidecar">Sidecar</a></h2><p>Postgres uses a separate backend process for each connection and limits how many can be open at once. Neki’s <strong>Sidecar</strong> sits in front of each instance and pools connections, letting many client connections share fewer Postgres backends.</p><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/neki-sidecar-highlight-LLGg_e2-.svg?auto=compress%2Cformat"><source media="(prefers-color-scheme: dark)" srcSet="https://planetscale-images.imgix.net/assets/neki-sidecar-highlight-darkmode-CSbhoWT-.svg?auto=compress%2Cformat"><img alt="A close-up of one Neki shard: the Router sends queries to a primary and replica, each with its own Sidecar highlighted in orange alongside Postgres, PostgresManager, and Replicator." src="https://planetscale-images.imgix.net/assets/neki-sidecar-highlight-LLGg_e2-.svg?auto=compress%2Cformat" width="704" height="555" loading="lazy"></picture></p><p>The Router, which is the component that accepts external client connections, communicates with the Postgres nodes via these Sidecars.</p><p>It also reports each Postgres instance&#x27;s health and whether it is a primary or replica, so the rest of the cluster knows whether it can receive write queries.</p><p>The pool doesn&#x27;t treat every connection the same way. The length of time a connection is checked out for use varies depending on what it&#x27;s being used for. A multi-statement transaction holds on to its connection until <code>commit</code> or <code>rollback</code>. A session-scoped advisory lock needs a connection of its own, because the lock has to outlive whatever transaction is open at the time and can&#x27;t share that connection. Everything else checks a connection out and hands it back the moment the statement finishes.</p><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/neki-sidecar-pooling-tiers-VAwYbEUp.svg?auto=compress%2Cformat"><source media="(prefers-color-scheme: dark)" srcSet="https://planetscale-images.imgix.net/assets/neki-sidecar-pooling-tiers-darkmode-D2UpeHY6.svg?auto=compress%2Cformat"><img alt="Three connection-pool lifetimes in the Sidecar: a shared connection for an autocommit statement, a dedicated connection for an open transaction, and a reserved connection for a session advisory lock." src="https://planetscale-images.imgix.net/assets/neki-sidecar-pooling-tiers-VAwYbEUp.svg?auto=compress%2Cformat" width="1504" height="454" loading="lazy"></picture></p><p>The Sidecar knows which of the three to use because the Router sends the necessary information with the query: autocommit, an open transaction, or a session that has to stay on one backend.</p><h2 id="shards"><a href="https://planetscale.com/blog/the-architecture-of-neki#shards">Shards</a></h2><p>Each Postgres instance gets its own Sidecar and PostgresManager pair. Real deployments need more than one instance: a primary and its replicas. Neki calls that group a <strong>shard</strong>, the unit it splits data across. It&#x27;s always advised to run a shard with a primary and 2+ replicas for high availability, as well as for additional read query capacity.</p><p>A shard is considered one Postgres cluster. Its replicas are physical copies of the primary, so they share a catalog and the same object identifiers.</p><p>Object Identifiers (OIDs) are how Postgres tracks objects internally, rather than by name. A client reads a column’s type OID off the wire to interpret its bytes and may cache that OID for later re-use. A custom type therefore needs to carry the same OID no matter which shard answers the query. Independent shards can assign that type different OIDs, so Neki designates one shard in the entire Neki cluster as the <strong>authoritative shard</strong>. This shard is the source of truth for translating custom type OIDs in responses from other shards to match. It ensures OIDs are consistent across the many shards of the Neki cluster.</p><p>The authoritative shard&#x27;s Sidecar also watches for schema changes and reports them to the Routers. This keeps the Routers&#x27; view of the schema current when a table is renamed or a column is dropped.</p><h2 id="admin"><a href="https://planetscale.com/blog/the-architecture-of-neki#admin">Admin</a></h2><p>In a distributed system, instances can fail independently while the rest of the system lives on. Neki is no different. A primary or replica can go down at any moment while its fellow instances on the shard are healthy. The <strong>Admin</strong>&#x27;s job is to detect failures, promote a replica, and maintain each shard’s durability policy.</p><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/neki-admin-highlight-utI4RFsa.svg?auto=compress%2Cformat"><source media="(prefers-color-scheme: dark)" srcSet="https://planetscale-images.imgix.net/assets/neki-admin-highlight-darkmode-DFbC_dyz.svg?auto=compress%2Cformat"><img alt="The same cluster diagram with Admin and the control plane highlighted and everything else faded." src="https://planetscale-images.imgix.net/assets/neki-admin-highlight-utI4RFsa.svg?auto=compress%2Cformat" width="1504" height="1058" loading="lazy"></picture></p><p>It health-checks every Sidecar, tracks replication lag for each replica, and decides when a shard needs a new primary. When a primary goes down, it coordinates an emergency failover, promoting a replica to take its place. It can also coordinate a planned switchover, which are needed for intentional node resizes and version upgrades. In both situations, Admin uses <code>pg_rewind</code> to bring diverged instances onto the new primary’s timeline, copying only the data that changed since the timelines diverged.</p><p>Each shard has a durability policy that determines when a commit is acknowledged:</p><ul><li><strong>Async:</strong> The primary acknowledges the commit without waiting for a replica.</li><li><strong>Sync:</strong> The primary waits for a replica to confirm the commit, protecting against the loss of a single node.</li><li><strong>Cross-zone sync:</strong> The primary waits for confirmation from a replica in another availability zone, protecting against the loss of the primary’s zone.</li></ul><p>Postgres enforces whichever one is configured, using its own synchronous replication machinery. The Admin keeps that configuration correct as replicas join or leave shards, or a failover moves the primary to a different zone.</p><p>Much of Admin’s work, however, doesn’t involve changing the primary. It repoints replicas to the correct replication source and corrects roles when Postgres and the topology disagree.</p><h2 id="operator"><a href="https://planetscale.com/blog/the-architecture-of-neki#operator">Operator</a></h2><p>Neki’s components need to be deployed, updated, and replaced when their machines fail. Neki is built Kubernetes-first, and the <strong>Operator</strong> manages this full lifecycle.</p><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/neki-operator-highlight-BSzSr8SQ.svg?auto=compress%2Cformat"><source media="(prefers-color-scheme: dark)" srcSet="https://planetscale-images.imgix.net/assets/neki-operator-highlight-darkmode-L_OKbSBD.svg?auto=compress%2Cformat"><img alt="The same cluster diagram with the Operator highlighted and everything else faded." src="https://planetscale-images.imgix.net/assets/neki-operator-highlight-BSzSr8SQ.svg?auto=compress%2Cformat" width="1504" height="1058" loading="lazy"></picture></p><p>The Operator models a cluster as a hierarchy. A cluster owns routers and shards, and each shard owns the pods running its Postgres instances and Sidecars. When the Neki cluster configuration changes, the Operator works out which pods need to be created, updated, or removed.</p><p>How it replaces an instance depends on whether that instance is still running. For a live instance, the Operator builds a replacement and confirms it has caught up before deleting the old one. If a node fails and loses its ephemeral storage, the Operator rebuilds the lost instance from scratch once its safety checks pass.</p><p>Admin and the Router handle the database side of those disruptions. Admin coordinates a switchover for planned primary replacements or a failover when a primary goes down. The Router can buffer queries that are safe to retry while a healthy primary becomes available.</p><h2 id="router"><a href="https://planetscale.com/blog/the-architecture-of-neki#router">Router</a></h2><p>We&#x27;ve talked a lot about how the Neki cluster operates and handles failure internally. What we&#x27;ve yet to dive into is how applications use the thing!</p><p>The <strong>Router</strong> is the entry point for clients connecting to a Neki cluster, presenting a single Postgres wire-protocol endpoint to connect to a (potentially) massive sharded database. Applications use Postgres drivers to send SQL and open transactions without managing connections to individual shards.</p><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/neki-router-highlight-Db72rv-H.svg?auto=compress%2Cformat"><source media="(prefers-color-scheme: dark)" srcSet="https://planetscale-images.imgix.net/assets/neki-router-highlight-darkmode-BBVEK1HZ.svg?auto=compress%2Cformat"><img alt="The same cluster diagram with the Router and etcd highlighted and everything else faded." src="https://planetscale-images.imgix.net/assets/neki-router-highlight-Db72rv-H.svg?auto=compress%2Cformat" width="1504" height="1058" loading="lazy"></picture></p><p>Authentication and role checks are done as if it were the Postgres instance itself, and the protocol&#x27;s own extended-query flow and prepared-statement lifecycle are all built into the Router.</p><p>Once a query arrives, the Router runs a Postgres-compatible parser against the authoritative shard&#x27;s catalog, plans it against the current sharding layout, and sends it to whichever Sidecar needs to run it over gRPC.</p><p>Not every query can run on a single shard. A join may need data from several shards or an aggregate may need to read from all of them. The <strong>Router</strong> coordinates that work as a <a href="https://planetscale.com/blog/what-is-a-neki-router">distributed query</a>.</p><p>Whenever possible, it leaves the work to the Postgres instances. If both sides of a join are on the same shard, the Router sends the join to that shard. When a join needs to run across shards, the Router executes it itself, choosing between nested-loop, hash, and merge joins based on cost estimations.</p><div class="mb-3 border p-3 border-blue-600 dark:border-blue-500"><p><span class="bg-blue-600 px-sm text-white dark:bg-blue-500 dark:text-black">Note</span></p><p>Read more about Routers, parsing, and sharded query planning in our other blog, <a href="https://planetscale.com/blog/the-lifecycle-of-a-sharded-postgres-query">The lifecycle of a sharded Postgres query</a>.</p></div><p>Earlier, we covered how Admin promotes a new primary during a switchover or failover. If that happens, the Router can buffer queries, giving the Admin time to complete the handover. For queries that can safely be retried after failing against a primary, the Router buffers the query and waits, for a fixed time, for a healthy primary. Once a healthy primary is available, the Router releases queued queries gradually.</p><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/neki-router-buffering-blWD4uWF.svg?auto=compress%2Cformat"><source media="(prefers-color-scheme: dark)" srcSet="https://planetscale-images.imgix.net/assets/neki-router-buffering-darkmode-Ck1ByFNK.svg?auto=compress%2Cformat"><img alt="A query hits an unavailable primary and gets buffered. Usually the primary recovers within the time and size limit and the queued query is released gradually, so the client sees nothing. Rarely, the limit is reached first and an error is returned to the client." src="https://planetscale-images.imgix.net/assets/neki-router-buffering-blWD4uWF.svg?auto=compress%2Cformat" width="1504" height="500" loading="lazy"></picture></p><h2 id="data-topology"><a href="https://planetscale.com/blog/the-architecture-of-neki#data-topology">Data Topology</a></h2><p>Router, Sidecars, and Admin all need a consistent picture of which shards exist, what key ranges they own, and which tables are sharded at all. If the Router&#x27;s copy is wrong, a query can land on the wrong shard. This is all specified with a <a href="https://planetscale.com/blog/what-is-a-data-topology">Data Topology</a>, and <strong>etcd</strong> holds the single, authoritative copy of it. When the Data Topology changes, the Router, Sidecars, and Admin pick up the updated configuration without a restart or manual synchronization.</p><p>The Data Topology defines <strong>shard groups</strong>, named sets of physical shards, each owning a range of routing keys. Each table belongs to a shard group. <strong>Shard indexes</strong> specify the columns or expressions and the strategy used to turn row values into routing keys. Those keys determine which shard receives each row.</p><h2 id="replicator"><a href="https://planetscale.com/blog/the-architecture-of-neki#replicator">Replicator</a></h2><p>As a database grows, its layout may need to change. Tables need to be imported, shards need to be split, and schemas need to change all while applications keep using the database.</p><p>Neki&#x27;s <strong>Replicator</strong> handles the data movement behind all such operations. It runs as a separate process colocated with a shard&#x27;s Sidecar and Postgres. It is responsible for copying existing rows to new destinations, and also keeping the data current by decoding changes from a Postgres logical replication stream and applying them as SQL.</p><p><picture class="block"><source media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" srcSet="https://planetscale-images.imgix.net/assets/neki-replicator-highlight-DMADfE-G.svg?auto=compress%2Cformat"><source media="(prefers-color-scheme: dark)" srcSet="https://planetscale-images.imgix.net/assets/neki-replicator-highlight-darkmode-BilIVgxG.svg?auto=compress%2Cformat"><img alt="A close-up of one Neki shard, with the separate Replicator beside each Postgres instance and its connection from Postgres highlighted in orange." src="https://planetscale-images.imgix.net/assets/neki-replicator-highlight-DMADfE-G.svg?auto=compress%2Cformat" width="704" height="385" loading="lazy"></picture></p><p>Three workflows use the Replicator:</p><ul><li><strong>MoveTables</strong> relocates a set of tables, including imports from an external Postgres instance</li><li><strong>Reshard</strong> redistributes data across shard key ranges, allowing a shard to be split when it outgrows its capacity</li><li><strong>OnlineDDL</strong> changes a table&#x27;s schema by building a shadow table alongside the original and keeping it current through the same change-data-capture pipeline MoveTables and Reshard use to relocate rows. A final rename swaps the new table into place. This supports changes such as repartitioning a table, alongside changes that would otherwise require a blocking operation.</li></ul><p>Once the data has been copied and the destination is caught up, the workflow switches from the original tables or shards to their replacements. This is the cutover. The Router uses the same buffering mechanism that handles primary changes for this step. It buffers queries during that switch and releases them afterward.</p><p>Together, these components let Neki scale Postgres horizontally while presenting a single database to applications.</p><h2 id="get-started"><a href="https://planetscale.com/blog/the-architecture-of-neki#get-started">Get started</a></h2><p>Neki is in Platform Preview right now.</p><p>Start a <a href="https://app.planetscale.com/new">Neki</a> cluster today: build on it from scratch, or import an existing Postgres database.</p>]]></content>
    <summary><![CDATA[Sharded Postgres, from the team behind Vitess]]></summary>
  </entry>
</feed>
