<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Sergey</title>
    <description>The latest articles on DEV Community by Sergey (@sazonov).</description>
    <link>https://dev.to/sazonov</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1439906%2F162ea686-673b-4e11-9f80-e9cb1377d707.jpg</url>
      <title>DEV Community: Sergey</title>
      <link>https://dev.to/sazonov</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/sazonov"/>
    <language>en</language>
    <item>
      <title>A Startup's Guide to Sharding Postgres</title>
      <dc:creator>Sergey</dc:creator>
      <pubDate>Wed, 25 Nov 2026 14:15:13 +0000</pubDate>
      <link>https://dev.to/sazonov/a-startups-guide-to-sharding-postgres-3eff</link>
      <guid>https://dev.to/sazonov/a-startups-guide-to-sharding-postgres-3eff</guid>
      <description>&lt;h2&gt;
  
  
  Intro
&lt;/h2&gt;

&lt;p&gt;Most projects begin with a single Postgres instance for data persistence, and that is the right call. For some of them - for the lucky ones - the data keeps growing until one database becomes expensive and risky to operate. Depending on the workload, there are different answers to scaling the database - sharding is one of them, but outside of system design interviews it is rarely discussed beyond the choice of a sharding key.&lt;/p&gt;

&lt;p&gt;We sharded Postgres at the application level for a write-heavy, data-intensive backend. We started with one instance, have since grown to several, and moved data between them while serving users without UX impact. This article covers why we did it, how it works, and what went wrong along the way. It is written for engineers at startups, where the budget matters as much as the architecture.&lt;/p&gt;

&lt;p&gt;This article was inspired by &lt;a href="https://hatchet.run/blog/postgres-survival-guide" rel="noopener noreferrer"&gt;The startup's Postgres survival guide&lt;/a&gt; by Alexander Belanger of Hatchet. That guide keeps a single Postgres instance healthy, and this one picks up when a single instance is no longer enough.&lt;/p&gt;

&lt;h2&gt;
  
  
  Table of Contents
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Our Context&lt;/li&gt;
&lt;li&gt;How Big Is Too Big&lt;/li&gt;
&lt;li&gt;Alternatives We Rejected&lt;/li&gt;
&lt;li&gt;Application-Level Sharding&lt;/li&gt;
&lt;li&gt;Rebalancing in Production&lt;/li&gt;
&lt;li&gt;CDC during Rebalancing&lt;/li&gt;
&lt;li&gt;Lessons Learned&lt;/li&gt;
&lt;li&gt;Recommended Reading&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Our Context
&lt;/h2&gt;

&lt;p&gt;We are a startup, not a deep-pocketed tech company, so cost and operational complexity drive most of our decisions.&lt;/p&gt;

&lt;p&gt;A few words about requirements and the nature of the application's data:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;data is naturally partitioned by the &lt;code&gt;user_id&lt;/code&gt; with no cross-user_id operations and low risk of hot partitions&lt;/li&gt;
&lt;li&gt;application is write-skewed&lt;/li&gt;
&lt;li&gt;writes go through Kafka, keyed by &lt;code&gt;user_id&lt;/code&gt;, and a consumer is the only writer to the database&lt;/li&gt;
&lt;li&gt;every write assigns the row a per-user sequence number in the same transaction, and clients sync incrementally by requesting rows above the last sequence they have seen&lt;/li&gt;
&lt;li&gt;deletes are soft (except for legal erasure such as GDPR)&lt;/li&gt;
&lt;li&gt;clients are &lt;a href="https://en.wikipedia.org/wiki/Local-first_software" rel="noopener noreferrer"&gt;local-first&lt;/a&gt; iOS and Android apps, with many app versions in the wild. They do not need the backend to be useful and may sync overnight while the phone charges, so latency matters little&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How Big Is Too Big
&lt;/h2&gt;

&lt;p&gt;Martin Kleppmann, in "Designing Data-Intensive Applications", calls a system data-intensive when its difficulty comes from the data (its volume, complexity, or rate of change) rather than from computation. I would add that "big" also depends on who is asking. What is big for a startup may be peanuts for an enterprise and a rounding error for Big Tech. For a startup driven by unit economics, a few terabytes of hot transactional data can already be a serious problem.&lt;/p&gt;

&lt;p&gt;Many projects start on a single Postgres instance and leave scaling to their future selves. I am guilty of this too: a couple of years ago I designed a project for ever-growing data with warm and cold storage, and cold storage never made it to production. Its largest table has since crossed our operational comfort limit, and the costs, risk, and headaches grew with it. The good news is that this project is moving into the sharded database I'm writing about.&lt;/p&gt;

&lt;h3&gt;
  
  
  What Breaks First
&lt;/h3&gt;

&lt;p&gt;Postgres has no hard limit on data size. The limits come from the operations around it:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Disaster recovery&lt;/strong&gt;: point-in-time restore of 1TB on AWS can take an hour, plus 1-4 hours of degraded performance while blocks lazily load from S3&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Vacuum and bloat&lt;/strong&gt;: &lt;code&gt;VACUUM FULL&lt;/code&gt; locks the table for hours, and &lt;code&gt;pg_repack&lt;/code&gt; needs free disk for a full copy of the table&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Schema changes&lt;/strong&gt;: a humble &lt;code&gt;ALTER COLUMN TYPE&lt;/code&gt; can rewrite and lock a huge table for hours&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Indexes&lt;/strong&gt;: index rebuilds take hours even with &lt;code&gt;CONCURRENTLY&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Replication and CDC&lt;/strong&gt;: replica provisioning takes hours if not days, and a stalled CDC consumer makes the slot hold WAL until it eats the free disk&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Human errors&lt;/strong&gt;: a bad migration has a big blast radius&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Most of these come down to disk headroom. Vacuum, reindex, &lt;code&gt;ALTER&lt;/code&gt;, and a lagging CDC slot all need free space on top of the data, and you often need it only for a few hours. But RDS (assuming you're on AWS) does not let you easily shrink allocated storage, so that headroom becomes a permanent part of your bill. At some point the headroom cost plus the size-dependent risks exceed the cost of one more, smaller instance.&lt;/p&gt;

&lt;p&gt;That gives us two limits:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;The unit of maintenance.&lt;/strong&gt; Vacuum, reindex, and repack work on one table or partition at a time, so headroom is sized by the largest one. We keep it under 100GB including indexes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The instance.&lt;/strong&gt; Sooner or later you move half of an instance's data to a new node (a "rebalance"), and the whole thing (copy, cut-over, clean-up, repack) should fit into one or two days. For us that means at most 1TB including indexes per instance.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We employ different strategies to manage those limits: partitioning to keep the unit of maintenance small and database sharding to keep instance size operationally manageable. We start preparing a rebalance no later than when the largest instance reaches 700GB. Splitting at 700GB leaves two instances of 350GB with plenty of room, while splitting at 950GB leaves 475GB each and another split soon. If you can predict a jump in data volume, say after a feature release, add instances before the data arrives.&lt;/p&gt;

&lt;h2&gt;
  
  
  Alternatives We Rejected
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Scaling Without Sharding
&lt;/h3&gt;

&lt;p&gt;Most of the usual options solve read load or CPU, not the size of one instance under heavy writes. A bigger instance buys CPU and memory, but restore time, vacuum, and headroom still grow with the data. Read replicas scale reads, while every write still lands on one primary and each replica multiplies the storage bill. Partitioning keeps the unit of maintenance small, and we use it for that, but the instance keeps growing. Archiving cold data to a LakeHouse means merging hot and cold data on the read path, with unpredictable latency and painful pagination and deduplication. Housekeeping, like dropping unused indexes, can free a surprising amount of space, but it is not a growth strategy.&lt;/p&gt;

&lt;h3&gt;
  
  
  NoSQL
&lt;/h3&gt;

&lt;p&gt;Naturally partitioned data with no cross-partition operations makes a NoSQL data model a real option. It is not impossible to build per-user transactional sequencing (a form of the &lt;a href="https://microservices.io/patterns/data/transactional-outbox.html" rel="noopener noreferrer"&gt;Transactional Outbox Pattern&lt;/a&gt;) on NoSQL. I built one on DynamoDB and still maintain it as part of another project. But it comes with hard trade-offs. You either duplicate data (secondary indexes, streams) or accept inefficient reads with several expensive round trips between the application and the database. Each NoSQL engine also brings its own constraints, such as limits on query response size or eventually consistent reads.&lt;/p&gt;

&lt;p&gt;Skipping the full trade-off analysis, I'll cherry-pick the considerations that ruled NoSQL out:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;DynamoDB&lt;/strong&gt; storage alone costs about $2.5k/month per 10TB on Standard tables, a Global Secondary Index likely doubles that, and for a write-heavy workload with a transactional sequence update on every write, writes cost even more.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Cassandra&lt;/strong&gt;, which we already run in a legacy project, writes CDC logs per node, so every write shows up once per replica and needs custom deduplication.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;ScyllaDB&lt;/strong&gt; recently &lt;a href="https://www.scylladb.com/source-available-faq/" rel="noopener noreferrer"&gt;discontinued&lt;/a&gt; its open-source releases, and the license came out comparable to DynamoDB.&lt;/li&gt;
&lt;li&gt;Finally, I was the only one on the development team with production NoSQL data modeling experience, and that is a risk in itself.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Postgres gave us transactions for the per-user sequence, mature CDC through Debezium, and expertise across the team.&lt;/p&gt;

&lt;h3&gt;
  
  
  NewSQL / Relational
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href="https://aws.amazon.com/rds/aurora/" rel="noopener noreferrer"&gt;AWS Aurora&lt;/a&gt;&lt;/strong&gt; bills storage, I/O, and instance hours separately, which makes it hard to predict and expensive for a startup. Its storage does shrink when data is removed, which solves the headroom problem, so run your own numbers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href="https://www.yugabyte.com" rel="noopener noreferrer"&gt;YugabyteDB&lt;/a&gt;&lt;/strong&gt; looks interesting, but its open-source version could change license as ScyllaDB and CockroachDB did.&lt;/p&gt;

&lt;h3&gt;
  
  
  PostgreSQL Sharding Solutions
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href="https://www.citusdata.com/" rel="noopener noreferrer"&gt;Citus&lt;/a&gt;&lt;/strong&gt; suits distributed queries and cross-shard joins, which we don't need. It adds a coordinator every query passes through, and RDS does not support it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href="https://pgdog.dev/" rel="noopener noreferrer"&gt;PgDog&lt;/a&gt;&lt;/strong&gt;, a sharding proxy with online resharding, is worth watching, but its Sharding 1.0 milestone was 41% done when we looked.&lt;/p&gt;

&lt;p&gt;These solutions add a layer for queries that span shards - something we do not need. They also do nothing for disk headroom or operational complexity, and they add a new dependency to manage.&lt;/p&gt;

&lt;h2&gt;
  
  
  Application-Level Sharding
&lt;/h2&gt;

&lt;p&gt;For the theory and other examples, see:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Shard_%28database_architecture%29" rel="noopener noreferrer"&gt;Shard (database architecture)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Instagram, &lt;a href="https://medium.com/instagram-engineering/sharding-ids-at-instagram-1cf5a71e5a5c" rel="noopener noreferrer"&gt;Sharding &amp;amp; IDs at Instagram&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Notion, &lt;a href="https://www.notion.com/blog/sharding-postgres-at-notion" rel="noopener noreferrer"&gt;Herding elephants: lessons learned from sharding Postgres at Notion&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fc2dblr18bruikcxcns61.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fc2dblr18bruikcxcns61.png" alt="The application server routes each request to one of several Postgres instances" width="800" height="522"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;With application-level sharding, the application decides which instance to talk to. Given a shard key, a small router (a class in the application code) looks up the instance in a config map, takes a connection from that instance's pool, and runs the query. Each instance is an ordinary Postgres that has no idea it is part of a cluster.&lt;/p&gt;

&lt;p&gt;In return, you own the router, the config, and the rebalancing tooling. There are no cross-shard transactions or joins, every migration runs on every instance, and cross-user analytics moves out of Postgres (for us, into a LakeHouse fed by CDC). When this fits your data model, it is the simplest and most reliable approach, and Instagram and Notion both took it.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Sharding Key
&lt;/h3&gt;

&lt;p&gt;A good sharding key is present in every query, never changes, and has high cardinality. &lt;code&gt;user_id&lt;/code&gt; meets all three. High cardinality still does not guarantee even load: paying users often generate more data, and a shard full of churned users gets quieter while one with new users gets busier. Virtual shards help smooth this out.&lt;/p&gt;

&lt;h3&gt;
  
  
  Virtual Sharding
&lt;/h3&gt;

&lt;p&gt;We wanted to start with one instance and add more as data grows, without ever moving all or most of the data across instances (a &lt;strong&gt;full resharding&lt;/strong&gt;). Naive sharding, &lt;code&gt;hash(user_id) % N&lt;/code&gt;, fails the second goal. Going from N to N+1 instances changes the modulus and moves roughly N/(N+1) of all users.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Virtual shards&lt;/strong&gt; break the direct link between the key and the instance. Every &lt;code&gt;user_id&lt;/code&gt; maps to a fixed virtual shard, &lt;code&gt;hash(user_id) % 512&lt;/code&gt;, and a small config maps ranges of virtual shards to physical instances. Adding an instance means moving only the virtual shards assigned to it, and the same mechanism can isolate a hot shard on its own instance. Use a hash that gives the same result in every language and process; we use MurmurHash3 over the string form of &lt;code&gt;user_id&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Frc4tr11w4h0mq8oldql8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Frc4tr11w4h0mq8oldql8.png" alt="user_id is hashed to a virtual shard, and the shard router maps the virtual shard to a database" width="800" height="210"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The router keeps a connection pool per instance and looks up the instance in O(1). The map lives in git and changes through a pull request, and connection strings live in a secret store. A mistake in the map sends writes to the wrong instance, so the application checks on startup that the ranges cover all 512 virtual shards with no gaps or overlaps. If one cluster ever runs out of capacity, several routers can send different groups of users to different clusters.&lt;/p&gt;

&lt;p&gt;Every row also stores &lt;code&gt;virtual_shard_id&lt;/code&gt;, at two bytes per row. Logical replication filters by it during rebalancing, since Postgres has no built-in MurmurHash3 to compute it on the fly, and the LakeHouse uses it to know which shard a row belongs to.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;How many virtual shards&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Changing this number means a full resharding, so choose carefully. It caps the number of physical instances and sets how finely you can move data. It should divide evenly by the instance counts you expect. Powers of two divide well by 1, 2, 4, 8, 16, and every rebalance can split a range exactly in half, but they divide poorly by 3, 5, or 6. Notion chose 480 because it divides by many small numbers. Our data is spread evenly, so we took 512 and split ranges in half.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To keep the terms straight: &lt;strong&gt;rebalancing&lt;/strong&gt; moves virtual shards between instances and keeps the hash and the shard count. &lt;strong&gt;Resharding&lt;/strong&gt; changes the scheme itself and moves most rows, and we designed the system so we never need it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Rebalancing in Production
&lt;/h2&gt;

&lt;p&gt;Take the simplest case, adding a second instance to a single-instance cluster. Source holds all 512 virtual shards, and the new Target should take 256-511.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Prepare&lt;/strong&gt; both instances: provision Target, apply migrations, enable logical replication on Source.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Copy&lt;/strong&gt; the data from Source to Target with logical replication filtered by &lt;code&gt;virtual_shard_id BETWEEN 256 AND 511&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Settle&lt;/strong&gt; Target: wait for the initial copy, let the lag drop, refresh statistics.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Cut over&lt;/strong&gt;: stop writes, wait for zero lag, switch reads and writes for 256-511 to Target, stop replication, resume writes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Fix index bloat&lt;/strong&gt; on Target.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Clean up&lt;/strong&gt; shards 256-511 on Source.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Everything except the cut-over runs with the application fully online. The cut-over is hard because replication must stop exactly when writes start going to Target, and the two cannot be made atomic. We call the time between stopping and resuming writes the &lt;strong&gt;cut-over window&lt;/strong&gt;. Reads keep working during it, but writes wait for a couple of minutes.&lt;/p&gt;

&lt;h3&gt;
  
  
  Preparation
&lt;/h3&gt;

&lt;p&gt;Most of the risk can be removed before the rebalance starts.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Set &lt;code&gt;wal_level = logical&lt;/code&gt; (on RDS, &lt;code&gt;rds.logical_replication&lt;/code&gt;) well ahead, ideally before production, because it needs a restart. Check &lt;code&gt;max_replication_slots&lt;/code&gt; and &lt;code&gt;max_wal_senders&lt;/code&gt;, since the rebalance and CDC both need slots.&lt;/li&gt;
&lt;li&gt;Run the same Postgres major version on both sides.&lt;/li&gt;
&lt;li&gt;Apply migrations to Target with your usual tooling, and freeze schema changes until the cut-over, because logical replication does not replicate DDL.&lt;/li&gt;
&lt;li&gt;Give both instances disk headroom for WAL, since replication and CDC slots hold it.&lt;/li&gt;
&lt;li&gt;Grant the replication user its role and read access only for the rebalance.&lt;/li&gt;
&lt;li&gt;Make sure you can stop all writers at once: disable their autoscaling and check that queue retention is far longer than the pause.&lt;/li&gt;
&lt;li&gt;Render scripts for this particular rebalance, so nobody edits SQL by hand during the window, and run the same scripts in integration tests first. Fill in a checklist as you go; it becomes your log and a source of optimization ideas for the next rebalance.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Copying with Logical Replication
&lt;/h3&gt;

&lt;p&gt;We use row-filtered logical replication, available since Postgres 15:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="c1"&gt;-- on Source&lt;/span&gt;
&lt;span class="k"&gt;CREATE&lt;/span&gt; &lt;span class="no"&gt;PUBLICATION&lt;/span&gt; &lt;span class="n"&gt;rebalance&lt;/span&gt;
  &lt;span class="k"&gt;FOR&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="n"&gt;your_table&lt;/span&gt; &lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;virtual_shard_id&lt;/span&gt; &lt;span class="k"&gt;BETWEEN&lt;/span&gt; &lt;span class="mi"&gt;256&lt;/span&gt; &lt;span class="k"&gt;AND&lt;/span&gt; &lt;span class="mi"&gt;511&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="k"&gt;WITH&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;publish_via_partition_root&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;  &lt;span class="c1"&gt;-- required for partitioned tables&lt;/span&gt;

&lt;span class="c1"&gt;-- on Target&lt;/span&gt;
&lt;span class="k"&gt;CREATE&lt;/span&gt; &lt;span class="no"&gt;SUBSCRIPTION&lt;/span&gt; &lt;span class="n"&gt;rebalance&lt;/span&gt;
  &lt;span class="no"&gt;CONNECTION&lt;/span&gt; &lt;span class="s1"&gt;'host=... dbname=... '&lt;/span&gt;
  &lt;span class="no"&gt;PUBLICATION&lt;/span&gt; &lt;span class="n"&gt;rebalance&lt;/span&gt;
  &lt;span class="k"&gt;WITH&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;copy_data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Set the replica identity first.&lt;/strong&gt; A row filter on a publication that publishes &lt;code&gt;UPDATE&lt;/code&gt; and &lt;code&gt;DELETE&lt;/code&gt; may only use columns from the table's replica identity, and the default (the primary key) does not include &lt;code&gt;virtual_shard_id&lt;/code&gt;. Postgres does not check this when you create the publication. &lt;code&gt;CREATE PUBLICATION&lt;/code&gt; succeeds, and then your application's updates and deletes on Source start failing with "Column used in the publication WHERE expression is not part of the replica identity". So change it before creating the publication:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="n"&gt;your_table&lt;/span&gt; &lt;span class="no"&gt;REPLICA&lt;/span&gt; &lt;span class="no"&gt;IDENTITY&lt;/span&gt; &lt;span class="k"&gt;FULL&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On partitioned tables, the row filter requires &lt;code&gt;publish_via_partition_root = true&lt;/code&gt;, and the replica identity does not propagate from the root, so &lt;strong&gt;set it on every partition&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;FULL&lt;/code&gt; has a price. On Source, every update and delete writes the whole old row to WAL. On Target before Postgres 16, every replicated update and delete finds its row with a sequential scan. The alternative is &lt;code&gt;REPLICA IDENTITY USING INDEX&lt;/code&gt; with a unique index that includes &lt;code&gt;virtual_shard_id&lt;/code&gt;, which costs one more, very inefficient index. Set &lt;code&gt;REPLICA IDENTITY DEFAULT&lt;/code&gt; back on the table and every partition at the cut-over, right after dropping the publication.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;copy_data&lt;/code&gt; (the default) copies the existing rows before streaming changes. Each table is copied in one long transaction, during which vacuum on Source cannot remove dead rows, and &lt;code&gt;max_sync_workers_per_subscription&lt;/code&gt; (2 by default) caps how many tables copy in parallel.&lt;/p&gt;

&lt;h3&gt;
  
  
  Settling the Target
&lt;/h3&gt;

&lt;p&gt;A table has finished its initial copy when it reaches sync state &lt;code&gt;r&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="c1"&gt;-- on Target&lt;/span&gt;
&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="n"&gt;srrelid&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;regclass&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;srsubstate&lt;/span&gt;
&lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;pg_subscription_rel&lt;/span&gt;
&lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;srsubstate&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'r'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Measure the lag on Source, not Target. &lt;code&gt;pg_stat_subscription&lt;/code&gt; on Target can look healthy while Target is far behind, and the reliable number comes from the replication slot:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="c1"&gt;-- on Source&lt;/span&gt;
&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="n"&gt;slot_name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
       &lt;span class="nf"&gt;pg_size_pretty&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;pg_current_wal_lsn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;confirmed_flush_lsn&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;AS&lt;/span&gt; &lt;span class="n"&gt;behind&lt;/span&gt;
&lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;pg_replication_slots&lt;/span&gt;
&lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;slot_name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'rebalance'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While the application writes, look for a small, stable lag; it reaches zero only after writes stop.&lt;/p&gt;

&lt;p&gt;A freshly copied table has no planner statistics, so the first minutes after the cut-over can get really slow. Autovacuum will analyze the tables on its own, but it takes a while, so let it finish before the window. Then check &lt;code&gt;last_analyze&lt;/code&gt; and &lt;code&gt;last_autoanalyze&lt;/code&gt; in &lt;code&gt;pg_stat_user_tables&lt;/code&gt; and run &lt;code&gt;ANALYZE&lt;/code&gt; by hand where needed. We learned this the hard way, when running &lt;code&gt;ANALYZE&lt;/code&gt; inside the window only made the window longer.&lt;/p&gt;

&lt;h3&gt;
  
  
  Cut-over
&lt;/h3&gt;

&lt;p&gt;Since stopping replication and switching writes cannot be atomic, you either make sure nothing is written during the switch or make the overlap harmless.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dual write&lt;/strong&gt; takes the second route: the application writes the moved shards to both instances while replication runs, and there is no pause. But a row must come out identical on both sides whichever write lands first, so the database cannot compute any value such as &lt;code&gt;now()&lt;/code&gt;, an id, or a counter. Our per-user sequence is assigned in the database, which rules dual write out, and it would also double write latency.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Rolling update&lt;/strong&gt; is a cheaper variant of dual write. Instead of writing to both instances, you roll out the new config gradually: old workers write to Source, which replicates to Target, and new workers write to Target directly. The same condition on writes applies.&lt;/p&gt;

&lt;p&gt;Since the per-user sequence rules out both dual write and rolling update, we &lt;strong&gt;pause writes&lt;/strong&gt;. Our local-first clients retry and do not need read-your-writes, and Kafka on the write path buffers writes, so users notice nothing. Without Kafka, rejecting writes for the window would work just as well for a local-first client.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbujbknlt65ibet625tne.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbujbknlt65ibet625tne.png" alt="Reads go from the API straight to the database, while writes go through Kafka and a worker" width="800" height="394"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  The procedure
&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;1. Stop all writers.&lt;/strong&gt; Scale the Kafka consumers to zero. Writes pile up in Kafka, reads keep working, and the window starts.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Wait for replication to settle.&lt;/strong&gt; Every table on Target is in state &lt;code&gt;r&lt;/code&gt;, and the lag on the Source slot is exactly zero.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Switch the shard map with writers still at zero.&lt;/strong&gt; If writers scale up together with the map change, their writes clash with the still-running replication and fail with &lt;code&gt;duplicate key&lt;/code&gt; errors.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Stop replication.&lt;/strong&gt; On Target, detach the subscription from its slot first, so the drop does not need a connection to Source:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt; &lt;span class="no"&gt;SUBSCRIPTION&lt;/span&gt; &lt;span class="n"&gt;rebalance&lt;/span&gt; &lt;span class="no"&gt;DISABLE&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;ALTER&lt;/span&gt; &lt;span class="no"&gt;SUBSCRIPTION&lt;/span&gt; &lt;span class="n"&gt;rebalance&lt;/span&gt; &lt;span class="k"&gt;SET&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;slot_name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;NONE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;DROP&lt;/span&gt; &lt;span class="no"&gt;SUBSCRIPTION&lt;/span&gt; &lt;span class="n"&gt;rebalance&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then drop the publication and the slot on Source, and set &lt;code&gt;REPLICA IDENTITY DEFAULT&lt;/code&gt; back.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Resume writers.&lt;/strong&gt; The consumers drain the Kafka backlog into Target, and the window ends.&lt;/p&gt;

&lt;p&gt;Step 5 is the point of no return. Until then, you roll back by reverting the map, because Source still has every row. Once consumers write to Target, Source falls behind, and going back would need replication in the opposite direction. That is why the map switch and the writer restart are separate changes.&lt;/p&gt;

&lt;h3&gt;
  
  
  After Cut-over: Index Bloat
&lt;/h3&gt;

&lt;p&gt;After the copy, indexes on Target were up to twice the size of the same index built from scratch. &lt;code&gt;copy_data&lt;/code&gt; inserts rows into tables whose indexes already exist. With random keys, such as UUIDs or hash-based deduplication keys, each insert lands on a random B-tree leaf, full pages split in half, and the halves never fill up again. An index built in one pass from sorted data packs its pages densely.&lt;/p&gt;

&lt;p&gt;The fix is a rebuild:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;REINDEX&lt;/span&gt; &lt;span class="k"&gt;INDEX&lt;/span&gt; &lt;span class="no"&gt;CONCURRENTLY&lt;/span&gt; &lt;span class="n"&gt;your_table_pkey&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;CONCURRENTLY&lt;/code&gt; keeps the table available, but it needs free disk for a full copy of the index, takes hours on large ones, and writes a lot of WAL for your CDC slot to process. Rebuild one index at a time, estimate the gain first with &lt;code&gt;pgstatindex&lt;/code&gt; from &lt;code&gt;pgstattuple&lt;/code&gt;, and check the result with &lt;code&gt;pg_relation_size&lt;/code&gt;. We do this after the cut-over, because bloat does not affect correctness and every hour of replication piles up WAL on Source.&lt;/p&gt;

&lt;h3&gt;
  
  
  Clean-up
&lt;/h3&gt;

&lt;p&gt;After the cut-over, Source still holds every row of the moved shards - they have to be cleaned. This sounds like the easy part, but it turned out to be the hardest: we delete a large share of the rows in the biggest tables.&lt;/p&gt;

&lt;p&gt;We have no index on &lt;code&gt;virtual_shard_id&lt;/code&gt; and do not want one, given its size and low selectivity, so finding the rows means scanning the table. Naive batching, &lt;code&gt;DELETE ... WHERE virtual_shard_id BETWEEN ... LIMIT n&lt;/code&gt; in a loop, degrades. Each batch scans from the start of the table past more and more dead rows, until a batch takes many minutes. &lt;code&gt;VACUUM&lt;/code&gt; between batches helps only for a while.&lt;/p&gt;

&lt;p&gt;Instead, we batch by physical location. Every row has a &lt;code&gt;ctid&lt;/code&gt; (block number and position in the block), and since Postgres 14 a &lt;code&gt;ctid&lt;/code&gt; range runs as a Tid Range Scan that reads only those blocks. So we walk the table in fixed chunks of blocks, one transaction per chunk:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;DELETE&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;your_table&lt;/span&gt;
&lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;ctid&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="s1"&gt;'(0,0)'&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;tid&lt;/span&gt; &lt;span class="k"&gt;AND&lt;/span&gt; &lt;span class="n"&gt;ctid&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="s1"&gt;'(512,0)'&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;tid&lt;/span&gt;
  &lt;span class="k"&gt;AND&lt;/span&gt; &lt;span class="n"&gt;virtual_shard_id&lt;/span&gt; &lt;span class="k"&gt;BETWEEN&lt;/span&gt; &lt;span class="mi"&gt;256&lt;/span&gt; &lt;span class="k"&gt;AND&lt;/span&gt; &lt;span class="mi"&gt;511&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="c1"&gt;-- next batch: (512,0) .. (1024,0), and so on up to the last block&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each batch now costs about the same, so the total time is predictable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Watch the WAL.&lt;/strong&gt; Every deleted row goes to WAL, and the CDC slot holds it until the consumer chews through millions of delete events. If you delete faster than CDC consumes, WAL eats the free disk. Throttle the batches and pause when the slot lag grows; we had to stop and resume several times.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Watch autovacuum.&lt;/strong&gt; Mass deletes trigger autovacuum, which competes for I/O and writes WAL of its own. Disabling it in the RDS parameter group did not work for us, only the per-table setting did:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="n"&gt;your_table&lt;/span&gt; &lt;span class="k"&gt;SET&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;autovacuum_enabled&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="c1"&gt;-- and back to true when the clean-up is done&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Even that is not a guarantee. In one rebalance, vacuum started anyway mid-clean-up, and together they pushed disk usage past the RDS storage autoscaling threshold. Keep an eye on the RDS I/O burst balance as well, because draining it degrades performance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Don't expect the disk back.&lt;/strong&gt; Postgres reuses the freed space for new rows, but the files do not shrink. That is fine for us, because Source grows back into the space it already pays for.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Another option&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Some applications can make &lt;code&gt;virtual_shard_id&lt;/code&gt; the first column of the primary key:&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;PRIMARY&lt;/span&gt; &lt;span class="k"&gt;KEY&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;virtual_shard_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Then both the clean-up and the replication filter get an index for free. But this affects query design, index size, foreign keys, uniqueness and deduplication, ORM support, and CDC.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  CDC during Rebalancing
&lt;/h2&gt;

&lt;p&gt;Every instance streams changes to our LakeHouse with Debezium through its own slot. The LakeHouse should not notice a rebalance: the copy must not look like new data, the hand-over must leave no gaps or duplicates, and the clean-up must not look like deletes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Start CDC on Target inside the cut-over window.&lt;/strong&gt; A CDC slot on Target during the copy would emit every copied row as an insert, millions of duplicates. So we create it after the lag reaches zero and before writers resume. Every change before that point reached the LakeHouse through Source, and every change after it comes through Target. The write pause gives us this boundary for free. Target's Debezium connector also runs with &lt;code&gt;snapshot.mode = never&lt;/code&gt;, since a default snapshot would cause the same flood.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Rewrite row ownership.&lt;/strong&gt; Each LakeHouse record carries the instance it came from, so after the cut-over we update that attribute for the moved shards.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ignore the clean-up deletes.&lt;/strong&gt; Soft deletes make this easy. Physical deletes in the stream come only from the clean-up or from legal erasure, which purges the LakeHouse through its own process, so CDC can safely skip them. Without soft deletes, it would need to know which shards moved and drop their deletes from Source.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mind the WAL on Source.&lt;/strong&gt; Until the cut-over, Source has two slots holding WAL, and &lt;code&gt;REPLICA IDENTITY FULL&lt;/code&gt; makes every change heavier. In a non-production rehearsal, WAL grew far more than we expected, and we had to drop the CDC connector and restore it later. Since then we watch both slots as closely as free disk.&lt;/p&gt;

&lt;h2&gt;
  
  
  Lessons Learned
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Shard from day one, even on one instance.&lt;/strong&gt; A router, virtual shards, and a &lt;code&gt;virtual_shard_id&lt;/code&gt; column cost almost nothing when data is small, and retrofitting them is a project of its own.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Shrink the cut-over window.&lt;/strong&gt; Only replication catch-up, the config switch, and stopping replication need stopped writes, and each of our rebalances kept less inside the window.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Plan by the clean-up.&lt;/strong&gt; The copy takes hours and the cut-over minutes, but the clean-up takes days.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Storage autoscaling is a one-way door.&lt;/strong&gt; A short spike during clean-up becomes a permanent cost.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Not every growth problem needs a new instance.&lt;/strong&gt; Rebuild bloated indexes first, or move virtual shards between existing instances.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Forecast, don't react.&lt;/strong&gt; The active part of a rebalance takes a couple of days, but planning, alignment, and infrastructure setup take weeks of calendar time, so track the largest instance's monthly growth.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Prefer writes the application controls.&lt;/strong&gt; Soft deletes and app-computed values keep CDC simple and dual write possible.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Run Postgres 16 or newer.&lt;/strong&gt; Row filters need 15, and 16 lets the subscriber use indexes for tables with &lt;code&gt;REPLICA IDENTITY FULL&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Test with several databases.&lt;/strong&gt; Cover the shard router and rebalance process with integration tests that run against several instances. Make sure your rebalance integration tests use &lt;strong&gt;exactly the same scripts&lt;/strong&gt; as the real rebalance, so the runbook and scripts are proven. Rehearse the first rebalance while the data is small.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;One size doesn't fit all.&lt;/strong&gt; If your clients need read-your-writes, or you have hard deletes and non-idempotent writes, a simple write pause may not be enough.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Recommended Reading
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Books
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;a href="https://www.amazon.com/dp/1098119061" rel="noopener noreferrer"&gt;Designing Data-Intensive Applications&lt;/a&gt;&lt;/strong&gt; by Martin Kleppmann and Chris Riccomini (2nd edition, O'Reilly, 2026). The chapters on replication, sharding, and stream processing explain the theory behind virtual shards, rebalancing, and CDC.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;a href="https://www.amazon.com/dp/1492086894" rel="noopener noreferrer"&gt;Software Architecture: The Hard Parts&lt;/a&gt;&lt;/strong&gt; by Neal Ford, Mark Richards, Pramod Sadalage, and Zhamak Dehghani (O'Reilly, 2021). It covers how to pull apart operational data and weigh the trade-offs of distributed data ownership.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;a href="https://www.amazon.com/dp/0321826620" rel="noopener noreferrer"&gt;NoSQL Distilled: A Brief Guide to the Emerging World of Polyglot Persistence&lt;/a&gt;&lt;/strong&gt; by Pramod Sadalage and Martin Fowler (Addison-Wesley, 2012). It is a short introduction to distribution models, sharding, and consistency trade-offs. Martin Fowler's &lt;a href="https://martinfowler.com/bliki/PolyglotPersistence.html" rel="noopener noreferrer"&gt;Polyglot Persistence&lt;/a&gt; note explains the idea in the title.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;a href="https://postgrespro.com/community/books/internals" rel="noopener noreferrer"&gt;PostgreSQL 14 Internals&lt;/a&gt;&lt;/strong&gt; by Egor Rogov (Postgres Professional, 2023, free PDF). It explains MVCC, vacuum, WAL, and index internals, which is where bloat and replication behavior come from.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Articles
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;a href="https://www.notion.com/blog/sharding-postgres-at-notion" rel="noopener noreferrer"&gt;Herding elephants: lessons learned from sharding Postgres at Notion&lt;/a&gt;&lt;/strong&gt; by Garrett Fidalgo (Notion, 2021). Notion sharded Postgres in the application with logical shards and moved data with a dual write and a backfill.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;a href="https://www.notion.com/blog/the-great-re-shard" rel="noopener noreferrer"&gt;The Great Re-shard: adding Postgres capacity (again) with zero downtime&lt;/a&gt;&lt;/strong&gt; by Arka Ganguli, Tanner Johnson, Ben Kraft, and Nathan Northcutt (Notion, 2023). The follow-up post moves logical shards to new instances with logical replication, close to the rebalancing described here.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;a href="https://www.figma.com/blog/how-figmas-databases-team-lived-to-tell-the-scale/" rel="noopener noreferrer"&gt;How Figma's databases team lived to tell the scale&lt;/a&gt;&lt;/strong&gt; by Sammy Steele (Figma, 2024). Figma took a different path and built horizontal sharding into a query proxy in front of Postgres.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>postgres</category>
      <category>database</category>
      <category>architecture</category>
      <category>backend</category>
    </item>
    <item>
      <title>Twelve Books I’ve read in 2024 as a Product Team Technical Leader</title>
      <dc:creator>Sergey</dc:creator>
      <pubDate>Mon, 06 Jan 2025 13:13:43 +0000</pubDate>
      <link>https://dev.to/sazonov/twelve-books-ive-read-in-2024-as-a-product-team-technical-leader-4eal</link>
      <guid>https://dev.to/sazonov/twelve-books-ive-read-in-2024-as-a-product-team-technical-leader-4eal</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;According to Darwin's Origin of Species, it is not the most intellectual of the species that survives; it is not the strongest that survives; but the species that survives is the one that is able best to adapt and adjust to the changing environment in which it finds itself.&lt;/em&gt;&lt;br&gt;
— &lt;strong&gt;Leon C. Megginson&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;I started 2024 by leading the architectural design for a complex, distributed, data-intensive feature, and eventually stepped up as a Tech Lead of a Product Team. Along the way, I realized I needed to deepen my skills in areas like product discovery, user experience, building solutions that truly deliver value to users and the business, as well as diving deeper into architecture, systems design, and delivery processes.&lt;/p&gt;

&lt;p&gt;As I’m not the fastest reader, I faced the challenge of fitting all these areas of improvement into my limited time - so I had to pick titles very wisely. The company I work for - Welltory - helped immensely by nudging our whole team onto a steep learning curve through recommended reading and an external coaching opportunity. That’s how the books by Marty Cagan and Teresa Torres landed on my list. The rest I handpicked to ensure both breadth and relevance to my work challenges, and it turned out great - I've got tons of value and inspiration reading these books. Moreover, I’ve found a number of titles on my list that perfectly complement each other, creating a broader and more complete vision.&lt;/p&gt;

&lt;p&gt;So here is my list with very brief reviews:&lt;/p&gt;




&lt;p&gt;When 2024 kicked off, I was neck-deep in one of the most exciting (and challenging) projects I've ever worked on - leading the architecture for a distributed, data-heavy feature within &lt;a href="https://welltory.com" rel="noopener noreferrer"&gt;Welltory Health app&lt;/a&gt;. Not long after, I leveled up to Tech Lead for a Product Team. Sounds cool, right? As any career challenge, this one required a ton of learning.&lt;/p&gt;

&lt;p&gt;I needed to get better at things like understanding users, designing solutions that actually solve their problems, and delivering real value to both users and the business. Oh, and on top of that, I wanted to dig deeper into architecture, systems design, and delivery workflows.&lt;/p&gt;

&lt;p&gt;Here’s the catch: I’m not a fast reader, and there’s only so much time in a day. So, I had to choose my learning resources carefully. Thankfully, the company I work for, Welltory, really came through by encouraging us to grow, sharing great book recommendations, and even offering external coaching. That’s how books by Marty Cagan and Teresa Torres ended up on my desk.&lt;/p&gt;

&lt;p&gt;The rest of my reading list? I handpicked it to make sure it covered a range of topics but stayed super relevant to my work. It worked out better than I expected! Not only did I learn a ton, but a lot of the books complemented each other, giving me a clearer, bigger picture of what I needed to grow as a Tech Lead and a member of a Product Team.&lt;/p&gt;

&lt;p&gt;My reading list can be divided into three categories:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Product Discovery and Delivery &lt;/li&gt;
&lt;li&gt;Systems Design&lt;/li&gt;
&lt;li&gt;Personal Productivity and Creativity&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Below is the reading list I put together, along with my thoughts on each book. I hope it might inspire you, too!&lt;/p&gt;

&lt;h2&gt;
  
  
  Product Discovery and Delivery
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. Empowered. Marty Cagan, Chris Jones (&lt;a href="https://www.amazon.com/EMPOWERED-Ordinary-Extraordinary-Products-Silicon/dp/111969129X?crid=2SBT4A1XCDB6I&amp;amp;dib=eyJ2IjoiMSJ9._Uk6Fuwj2Rm2wDwOy60Hz1dC1cB059zkLePCIptzpqfE_W94u36nj7uFL4J2rid5CgtnnzWoxrFMzo5EHDlLo_xtx7TtTHFPuOP2mskr8r6awLEM2WlboB3XhoP_OvydzHhd0dtTfInHFbHgzjp75ilZ6o4N5IP4ATw3fMGSKFOm8TkBDKstztE9a0_bKY4gTMkgDhodQ_FIMaZY-fP2I6aMt0s1ZEZeo5CwYYzJhGM.qpDmXpQhILoYao29tD3udgy0e0j6EISn8V6cyUwxVHA&amp;amp;dib_tag=se&amp;amp;keywords=empowered&amp;amp;qid=1734870253&amp;amp;s=books&amp;amp;sprefix=empowere%2Cstripbooks-intl-ship%2C227&amp;amp;sr=1-1" rel="noopener noreferrer"&gt;Amazon&lt;/a&gt;, &lt;a href="https://www.audible.com/pd/Empowered-Audiobook/1663709777?eac_link=nv2U1sN4qpBz&amp;amp;ref=web_search_eac_asin_2&amp;amp;eac_selected_type=asin&amp;amp;eac_selected=1663709777&amp;amp;qid=b3NRWosRPk&amp;amp;eac_id=138-0708236-4963718_b3NRWosRPk&amp;amp;sr=1-2" rel="noopener noreferrer"&gt;Audible&lt;/a&gt;)
&lt;/h3&gt;

&lt;p&gt;Addressed to managers of Product Teams and Product Leaders, but definitely a must-read for Product Managers, Product Designers, and Tech Leads. The book highlights the significance of trust, autonomy, and accountability, emphasizes the role of coaching, and provides advice and tools for running discovery and delivery while managing stakeholders and building their trust.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Transformed. Marty Cagan, Lea Hickman, Chris Jones, Christian Idiodi, John Moore (&lt;a href="https://www.amazon.com/Transformed-Moving-Product-Operating-Silicon-ebook/dp/B0CXG97J55?crid=2PLI86U3A746R&amp;amp;dib=eyJ2IjoiMSJ9.U5sTexIkJhX3hmj9oCWbqCwY_1tBhQCpc-IpQbwlvh8F_6LF2vCFgxORLkjWK0Qxt-0JjDrbSlkUCNpRBPhUCX4HiEI7vX2BxB9HWMRKKlfAxgLVKfHYsgYLBYRLQ_drnzqXFyAacO23dnintOKCHg7gmJtrlg7Bmku8LgshkEIItHIzJ4H4h7goLfZ3BKr-ZW6vN4aInlnSSep6GUp5hUUyTD3JCTucbaOaVHbox38.0CaUpNyBvEeldgUDUKvapwubNM6vmiD7mbf9xs8Tl_E&amp;amp;dib_tag=se&amp;amp;keywords=transformed&amp;amp;qid=1734870588&amp;amp;s=digital-text&amp;amp;sprefix=tranformed%2Cdigital-text%2C198&amp;amp;sr=1-1" rel="noopener noreferrer"&gt;Amazon&lt;/a&gt;, &lt;a href="https://www.audible.com/pd/Transformed-Audiobook/B0CV5TZ3R7?qid=1734870581&amp;amp;sr=1-1&amp;amp;ref_pageloadid=not_applicable&amp;amp;pf_rd_p=83218cca-c308-412f-bfcf-90198b687a2f&amp;amp;pf_rd_r=WPA95JMTNREQYZ887D6S&amp;amp;plink=ftrcySNqxSCaus5g&amp;amp;pageLoadId=32P0fnyEq1Ge5u07&amp;amp;creativeId=0d6f6720-f41c-457e-a42b-8c8dceb62f2c&amp;amp;ref=a_search_c3_lProduct_1_1" rel="noopener noreferrer"&gt;Audible&lt;/a&gt;)
&lt;/h3&gt;

&lt;p&gt;A practical, case-based look at how teams and companies can move to a product-based operating model. I really appreciated the diverse perspectives and real-world transformation examples. An essential read for Product Team members - pairs nicely with &lt;em&gt;Continuous Discovery Habits&lt;/em&gt; by Teresa Torres, &lt;em&gt;Lean UX&lt;/em&gt; by  Jeff Gothelf and Josh Seiden and &lt;em&gt;Clean Agile&lt;/em&gt; by Robert Martin.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Continuous Discovery Habits. Teresa Torres  (&lt;a href="https://www.amazon.com/Continuous-Discovery-Habits-Discover-Products-ebook/dp/B094PVB97X?crid=3CEEQ3RD899WS&amp;amp;dib=eyJ2IjoiMSJ9.mK8-Cv8_wY50EpayvfqABe8zMQJhsR7duuFSHpO68qjcYdUAS1ivmNrlZtCGTGIsBz6r62N2y3pYknG05FKRPHu9gow3WHPkW6yWIMZ2D-dcOR5EEPEX_gMBDgy5MF3KtYvNENreYwjXj1i7cLE5hHfersC4Sb-23Fmb7nNqWe2FdcH8ar8w0uOe3Wo2shz1urB35tbXznwmwkTkM6EIBKUThhz5kLtYXliPMcu05V8.FUa6TjFV9a4-vmvORtOoIGe1wJxTwm67wMq7Z7NHFcw&amp;amp;dib_tag=se&amp;amp;keywords=continuous+discovery+habits&amp;amp;qid=1734870956&amp;amp;s=digital-text&amp;amp;sprefix=continous+disco%2Cdigital-text%2C234&amp;amp;sr=1-1" rel="noopener noreferrer"&gt;Amazon&lt;/a&gt;, &lt;a href="https://www.audible.com/pd/Continuous-Discovery-Habits-Audiobook/B09XZGNP41?qid=1734870967&amp;amp;sr=1-1&amp;amp;ref_pageloadid=not_applicable&amp;amp;pf_rd_p=83218cca-c308-412f-bfcf-90198b687a2f&amp;amp;pf_rd_r=Y44P9C2W7PEVC8SNR66N&amp;amp;plink=QD3TxJggJIlmWIJP&amp;amp;pageLoadId=b6RGEzhgWGWhOqcM&amp;amp;creativeId=0d6f6720-f41c-457e-a42b-8c8dceb62f2c&amp;amp;ref=a_search_c3_lProduct_1_1" rel="noopener noreferrer"&gt;Audible&lt;/a&gt;)
&lt;/h3&gt;

&lt;p&gt;This one shines when paired with Marty Cagan’s books, &lt;em&gt;Clean Agile&lt;/em&gt; and &lt;em&gt;Lean UX&lt;/em&gt;. Torres offers a distilled framework for weaving continuous discovery into the day-to-day work of Product Team. The techniques focus not just on gathering and acting upon user feedback but also on understanding real user behaviors. A must read for aspiring Tech Lead. &lt;/p&gt;

&lt;h3&gt;
  
  
  4. Lean UX: Designing Great Products with Agile Teams. Jeff Gothelf and Josh Seiden (&lt;a href="https://www.amazon.com/Lean-UX-Designing-Great-Products/dp/1491953608" rel="noopener noreferrer"&gt;Amazon&lt;/a&gt;, &lt;a href="https://www.audible.com/pd/Lean-UX-Designing-Great-Products-with-Agile-Teams-Second-Edition-Audiobook/B08VL2NTZT?qid=1735746578&amp;amp;sr=1-1&amp;amp;ref_pageloadid=not_applicable&amp;amp;pf_rd_p=83218cca-c308-412f-bfcf-90198b687a2f&amp;amp;pf_rd_r=WQEGN70P52BXMRZ4QMGJ&amp;amp;plink=4qUacUArSVBFNlBr&amp;amp;pageLoadId=0RBWFqQoCpK6XmQg&amp;amp;creativeId=0d6f6720-f41c-457e-a42b-8c8dceb62f2c&amp;amp;ref=a_search_c3_lProduct_1_1" rel="noopener noreferrer"&gt;Audible&lt;/a&gt;)
&lt;/h3&gt;

&lt;p&gt;A concise, practical companion to &lt;em&gt;Continuous Discovery Habits&lt;/em&gt;, this book focuses more on building processes  and habits of discovery, rapid experimentation, and continuous feedback across Product Teams than on “traditional” UX techniques. It portrays Product Designers as facilitators of collaborative design and discovery efforts - rather than isolated individual contributors - which resonates with me. If you’re looking to embed a habit of iterative learning and team-centric experimentation in your organization, &lt;em&gt;Lean UX&lt;/em&gt; is definitely worth the read.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Team Topologies: Organizing Business and Technology Teams for Fast Flow. Matthew Skelton and Manuel Pais (&lt;a href="https://www.amazon.com/Team-Topologies-Organizing-Business-Technology/dp/1942788819?crid=PMIJZEEHI4H1&amp;amp;dib=eyJ2IjoiMSJ9.fkrIHqMAVF-HH87KlVLrbPvwjPCCnMjBq8gIei14er9TJGufa7FUKxBvJbszE6-0p0EWV1x_P3LeYInO5FgJnzn0kCvA0qvkYfUTAjdO28Yzr1Gf2ueLvX6h7VyeaoVcBVO4kLYe8SGO_cijPyo9JfLDC-Uq_dGCFbjxSnQbno9rR4qndyvsqhA2Oyeg47LeUePQIhKHbD1MYWjPFlAgROZTDbtuVQZ3Z_-JngPtEIY.BdoVg1hAtwkdn9h9pWRe6GqZ_GBkFqjmdu1DeqIcFKY&amp;amp;dib_tag=se&amp;amp;keywords=team+topologies&amp;amp;qid=1734871060&amp;amp;s=books&amp;amp;sprefix=team+topo%2Cstripbooks-intl-ship%2C202&amp;amp;sr=1-1" rel="noopener noreferrer"&gt;Amazon&lt;/a&gt;, &lt;a href="https://www.audible.com/pd/Team-Topologies-Organizing-Business-and-Technology-Teams-for-Fast-Flow-Audiobook/B07VZ2JKQP?qid=1734871069&amp;amp;sr=1-1&amp;amp;ref_pageloadid=not_applicable&amp;amp;pf_rd_p=83218cca-c308-412f-bfcf-90198b687a2f&amp;amp;pf_rd_r=HPG1B5PKY3X25PD6PA1N&amp;amp;plink=CJyqiZfA2b1qSlZy&amp;amp;pageLoadId=69rkJFis5m7gvWVy&amp;amp;creativeId=0d6f6720-f41c-457e-a42b-8c8dceb62f2c&amp;amp;ref=a_search_c3_lProduct_1_1" rel="noopener noreferrer"&gt;Audible&lt;/a&gt;)
&lt;/h3&gt;

&lt;p&gt;Introduces tons of concepts - like different team topologies and managing team cognitive capacity - that helped me make sense of the dynamics I’ve observed across various teams. There are plenty of patterns and anti-patterns, all backed by research or real-world case studies, showing how to optimize flow and better align teams with business objectives. As a Tech Lead, I found the framework especially handy for improving cross-team communication and staying mindful of cognitive load of a team.&lt;/p&gt;

&lt;h3&gt;
  
  
  6. Clean Agile. Robert Martin (&lt;a href="https://www.amazon.com/Clean-Agile-Basics-Robert-Martin-ebook/dp/B07XTL99JQ?_encoding=UTF8&amp;amp;dib_tag=se&amp;amp;dib=eyJ2IjoiMSJ9.2TNoJmRxXbWHkNrhUTUjh5cF9ggp4iM3gRdFRIUL_rTDpZ1X6CILJVaKf27P0ntVzM5zgoQnYR4RJhb9l6SR0HKjAg86ScnnbQzQAggBgAfH4UdL4TBDGCF0WBWs7B5beDz20o3h3u_D0C_Om1OoJQ.PR-0UkU5zSAIP44kIdRE79Y21UNTCIexaB2UHdl6yXU&amp;amp;qid=1734870513&amp;amp;sr=1-1" rel="noopener noreferrer"&gt;Amazon&lt;/a&gt;, &lt;a href="https://www.audible.com/pd/Clean-Agile-Audiobook/B08X7D3YFR?qid=1734870489&amp;amp;sr=1-1&amp;amp;ref_pageloadid=not_applicable&amp;amp;pf_rd_p=83218cca-c308-412f-bfcf-90198b687a2f&amp;amp;pf_rd_r=88AR1PPGH9MXVYWE7QKR&amp;amp;plink=fGeAruDNSa0XVZ7E&amp;amp;pageLoadId=G75HZEdeeexvtBLF&amp;amp;creativeId=0d6f6720-f41c-457e-a42b-8c8dceb62f2c&amp;amp;ref=a_search_c3_lProduct_1_1" rel="noopener noreferrer"&gt;Audible&lt;/a&gt;)
&lt;/h3&gt;

&lt;p&gt;A very brief, straight-to-the-point re-introduction to Agile, reminding us what those core principles really mean in practice - beyond the usual ceremonies and rituals. It pairs seamlessly with works by Marty Cagan and Teresa Torres on product-centric, discovery-driven approaches. Personally, I felt inspired to gradually refine our backlog and delivery practices to adopt TDD and Continuous Delivery (in broader terms that what you see in CI/CD pipelines), better aligning our team with continuous discovery and the delivery of value to user and business.&lt;/p&gt;

&lt;h2&gt;
  
  
  Systems Design
&lt;/h2&gt;

&lt;h3&gt;
  
  
  7. Designing Data Intensive Applications. Martin Kleppmann  (&lt;a href="https://www.amazon.com/Designing-Data-Intensive-Applications-Reliable-Maintainable/dp/1449373321?crid=2L5HEGY7FA6W2&amp;amp;dib=eyJ2IjoiMSJ9.qKMpaeqG8Tk9d-cfMY0ga-12ydPbEIyi-xZgKi01GOPEXwEFY3uGawMhqGD37Na53EmpX5bpV9taT34H935Gj5lbNEDTyRkzoN3UvsNIzCJQNn1r46XpHX-Dspt_lX0R6VIDaOj9pPgaAOd31j0j7v06sXbtg3zmWoFzIE8QDkVI1OROkQRRxfetcNrd6Rfz_CU2HHz3iLziBXt5SnmiZdOyeF5_AFfgXsCwpVz0xxg.KGp8w7YW7QvZdtATLT2lCvHwG8JAcQPpUwwHf2kTMQo&amp;amp;dib_tag=se&amp;amp;keywords=designing+data-intensive+applications&amp;amp;qid=1734870183&amp;amp;s=books&amp;amp;sprefix=designing+data%2Cstripbooks-intl-ship%2C228&amp;amp;sr=1-1" rel="noopener noreferrer"&gt;Amazon&lt;/a&gt;, &lt;a href="https://www.audible.com/pd/Designing-Data-Intensive-Applications-Audiobook/B08VLGDK32?eac_link=YXHwNblLCQnk&amp;amp;ref=web_search_eac_asin_2&amp;amp;eac_selected_type=asin&amp;amp;eac_selected=B08VLGDK32&amp;amp;qid=SxpcRjC1mA&amp;amp;eac_id=138-0708236-4963718_SxpcRjC1mA&amp;amp;sr=1-2" rel="noopener noreferrer"&gt;Audible&lt;/a&gt;)
&lt;/h3&gt;

&lt;p&gt;By far the most important piece of wisdom on distributed systems and data-intensive applications I've read. This is my technology bible - I’ve read it twice and refer to it at least weekly for an inspiration in solving real-life architecture problems.&lt;/p&gt;

&lt;p&gt;Apart from incredible value of content, two other characteristics of the book impressed me:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Despite the book’s depth and complexity, it’s surprisingly consumable as an audiobook.&lt;/li&gt;
&lt;li&gt;It’s very easy to comprehend. I was a bit intimidated before starting, but now I see it’s very approachable. Certain parts may even inspire less-technical roles like Product Managers - particularly “Chapter 12. The Future of Data Systems.”&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Looking forward to 2nd edition later this year!&lt;/p&gt;

&lt;h3&gt;
  
  
  8. Fundamentals of Software Architecture. An Engineering Approach. Mark Richards and Neal Ford (&lt;a href="https://www.amazon.com/Fundamentals-Software-Architecture-Engineering-Approach/dp/B08X8H15BW?crid=9G30ATFHT82Y&amp;amp;dib=eyJ2IjoiMSJ9.JlSyji6FLRpvHFfg1g_3l2W3FTiongnl-TVtWhRfnHSqj1aiXFXWxM-RvPctQ5rNcijrf2BEnCHN8Zel-eTlNk0jTTa_Q2LYbr7xu0lu9wH6cKSOXoY3BTsMPlYezcOvQN4nfy45joIbjADVthasKcZkVozbk4mlFrp2fUIa1FpaM_ru01PQKo-cHISX8q_FfZGMPwouzrDdYBYxWZkuLS4nqJhGwMvPD2_DJlXlQVE.amZgOixK8PXsSheZ3NMGCm2-dkdoV8CKy3B6E4SQKE8&amp;amp;dib_tag=se&amp;amp;keywords=Fundamentals+of+Software+Architecture&amp;amp;qid=1734870352&amp;amp;s=books&amp;amp;sprefix=fundamentals+of+software+architecture%2Cstripbooks-intl-ship%2C361&amp;amp;sr=1-1" rel="noopener noreferrer"&gt;Amazon&lt;/a&gt;, &lt;a href="https://www.audible.com/pd/Fundamentals-of-Software-Architecture-Audiobook/B08X917VLR?qid=1734870345&amp;amp;sr=1-1&amp;amp;ref_pageloadid=not_applicable&amp;amp;pf_rd_p=83218cca-c308-412f-bfcf-90198b687a2f&amp;amp;pf_rd_r=CXGS9QRVN3PDB8237ZT7&amp;amp;plink=2XreMZmmWfbd732q&amp;amp;pageLoadId=BuPPNOV5k6jvCJ7t&amp;amp;creativeId=0d6f6720-f41c-457e-a42b-8c8dceb62f2c&amp;amp;ref=a_search_c3_lProduct_1_1" rel="noopener noreferrer"&gt;Audible&lt;/a&gt;)
&lt;/h3&gt;

&lt;p&gt;A fundamental deep dive into software architecture characteristics, metrics, and patterns, packed with tons of practical advice and tools for designing, communicating, and implementing systems effectively. There’s a big emphasis on maintaining architectural compliance and evolution, plus a focus on the soft skills needed to guide teams. Overall, it’s very well structured and highly approachable - an essential read for anyone looking to solidify their architectural chops.&lt;/p&gt;

&lt;h3&gt;
  
  
  9. Clean Architecture. Robert Martin (&lt;a href="https://www.amazon.com/Clean-Architecture-Craftsmans-Software-Structure-ebook/dp/B075LRM681?crid=2VRRJF62TC01H&amp;amp;dib=eyJ2IjoiMSJ9.mcwhwAcECXs-NuEmL5TaW2Jo-v5tTiEUKfajkKJCMoRbTfUaWxpVZW8jkg0Ds2pwbJ2TtYJUAO6621Ble4qv82Iv4mLBabiFUb2tpyZuaKS-TZVYPXlW53TTHROxcq-n7FB7OZq_j45oyjcdsY-HhJiFA2f8vGFrP51xWTOx6vUE8pTnEYmcKh8Y0eCGXlrb-2S3gPpMXf0sNvk6Ow3-f0Dto3dEOYjKScUAcASKa78.ghbowhi_sezyL7eZCz-Dp31c8zrGqj5Uf0hjWZ9qxBI&amp;amp;dib_tag=se&amp;amp;keywords=clean+architecture&amp;amp;qid=1734870862&amp;amp;s=digital-text&amp;amp;sprefix=clean+architectur%2Cdigital-text%2C213&amp;amp;sr=1-1" rel="noopener noreferrer"&gt;Amazon&lt;/a&gt;, &lt;a href="https://www.audible.com/pd/Clean-Architecture-Audiobook/B08X8L9MJZ?eac_link=nPbEQlplDWTJ&amp;amp;ref=web_search_eac_asin_1&amp;amp;eac_selected_type=asin&amp;amp;eac_selected=B08X8L9MJZ&amp;amp;qid=7XFxmuNyGU&amp;amp;eac_id=138-0708236-4963718_7XFxmuNyGU&amp;amp;sr=1-1" rel="noopener noreferrer"&gt;Audible&lt;/a&gt;)
&lt;/h3&gt;

&lt;p&gt;A strong and somewhat more practical complement to &lt;em&gt;Fundamentals of Software Architecture&lt;/em&gt; by Mark Richards and Neal Ford. “Uncle Bob” once again shares his wisdom, backed by real-life stories and anecdotes. I’ve seen measurable positive impact after weaving these strategies into my team’s processes and feature design - it’s definitely worth reading.&lt;/p&gt;

&lt;h3&gt;
  
  
  10. NoSQL Distilled. A Brief Guide to the Emerging World of Polyglot Persistence. Pramod J. Sadalage, Martin Fowler  (&lt;a href="https://www.amazon.com/NoSQL-Distilled-Emerging-Polyglot-Persistence/dp/0321826620/ref=sr_1_1?crid=2VH71D6HU8QZQ&amp;amp;dib=eyJ2IjoiMSJ9.gVPeYA6BXDbK5Qg9Ve2jtMom6Wp4b3Jdwu1pUN5jTqbGjHj071QN20LucGBJIEps.R2E9d2L-EWoYb78htWP9w5ATOVL72zgCQJv_wGtqm4c&amp;amp;dib_tag=se&amp;amp;keywords=NoSQL+Distilled.+A+Brief+Guide+to+the+Emerging+World+of+Polyglot+Persistence&amp;amp;qid=1736075268&amp;amp;s=books&amp;amp;sprefix=%2Cstripbooks-intl-ship%2C491&amp;amp;sr=1-1" rel="noopener noreferrer"&gt;Amazon&lt;/a&gt;)
&lt;/h3&gt;

&lt;p&gt;Despite being quite short, the book felt fundamental to me. The authors dive into the key concepts of databases and distributed systems, starting with Relational Databases and moving on to various flavors of NoSQL and beyond. Sadalage and Fowler walk you through different NoSQL data models and the concept of polyglot persistence - choosing the right tool for each job rather than forcing a single solution. This book won’t go super deep on any single technology, but it’s excellent for building breadth in your understanding of available options.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A few notes:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The book dates back to 2012, so some details may be outdated - though the core principles remain strong. Some of the DBMSs mentioned aren’t heard of much anymore, while others have evolved significantly, and new players have entered the scene.&lt;/li&gt;
&lt;li&gt;The chapter recaps (“Key Points”) are simply amazing.&lt;/li&gt;
&lt;li&gt;This is a great source of "Further reading" suggestions if you’re keen to explore distributed systems and data stores more deeply.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  11. The DynamoDB Book. Alex DeBrie (&lt;a href="https://www.amazon.com/DynamoDB-Book-Alex-DeBrie/dp/B0BN7S1GQK" rel="noopener noreferrer"&gt;Amazon&lt;/a&gt;)
&lt;/h3&gt;

&lt;p&gt;We extensively use DynamoDB in my team, but reading this book made me realize we’d only scratched the surface - particularly when it comes to managing complex relationships and implementing single-table designs. Alex shares inspiration I needed in my thinking of possible options to evolve my team's product as we approach (financially sensible) scalability limits of a relational database. &lt;/p&gt;

&lt;p&gt;The writing itself is both educational and occasionally humorous - with nice little quirks like attributing Satya Nadella to Google in one of the data model examples. My only wish is that the author had gone deeper on why DynamoDB might be preferable over other NoSQL options like Cassandra or MongoDB. Overall, important read for anyone serious about modern Systems Design.&lt;/p&gt;

&lt;h2&gt;
  
  
  Personal Productivity and Creativity
&lt;/h2&gt;

&lt;h3&gt;
  
  
  12. Building a Second Brain. Tiago Forte (&lt;a href="https://www.amazon.com/Building-Second-Brain-Organize-Potential/dp/1982167386?crid=LWBB6ZQIDI9F&amp;amp;dib=eyJ2IjoiMSJ9.9qeW84-SbFAOg44UY11scobX7Vpx3ktZZnAicZu74hiATpbSHVNqmSPwrII9EfoBCH_o1F8x-aMXPgXsquzBhWu3NS3X2-VDzI-sDyXYy3zl42fxB6EYijPMrU6YxoCtWr5uIMT3xIF_gUSDUTGVXHtArUicGptHd7hqsHBcEIYqyoGWkircTApclzlkBFHVPpHDRJK-2YvGkoH2rOdzlly2U9XmcEMIo4U0wTIiZPw.a_3yodVu31VZftPS58ZtFkCZ31ON4caEsxu6Ohw2njQ&amp;amp;dib_tag=se&amp;amp;keywords=building+a+second+brain&amp;amp;qid=1734870097&amp;amp;s=books&amp;amp;sprefix=building+a+second+brain%2Cstripbooks-intl-ship%2C212&amp;amp;sr=1-1" rel="noopener noreferrer"&gt;Amazon&lt;/a&gt;, &lt;a href="https://www.audible.com/pd/Building-a-Second-Brain-Audiobook/B09MGHPVP4?eac_link=UqUUrrrZ5qYa&amp;amp;ref=web_search_eac_asin_1&amp;amp;eac_selected_type=asin&amp;amp;eac_selected=B09MGHPVP4&amp;amp;qid=h3LOaBFo05&amp;amp;eac_id=138-0708236-4963718_h3LOaBFo05&amp;amp;sr=1-1" rel="noopener noreferrer"&gt;Audible&lt;/a&gt;)
&lt;/h3&gt;

&lt;p&gt;Finally, I’ve found a note-taking and research-and-creativity framework that really works for me. The book is definitely worth reading, although the motivational tone sometimes takes center stage and slightly overshadows the practical advice.&lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;These twelve books have helped me expand beyond just the technical elements of software architecture to include product discovery, user experience, and team organization - all of which are crucial for my day-to-day challenges. By diving into topics such as continuous discovery, designing data-intensive applications, team topologies, and agile methodologies, I’ve gained a more holistic perspective on how to deliver real value to both users and the business.&lt;/p&gt;

&lt;p&gt;But this is just the beginning of the journey. I’m always looking for more books that address the multifaceted challenges of leading a product-focused tech team. If you have any recommendations or hidden gems that you’ve found particularly valuable, please let me know - I’d love to add them to my reading list!&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“Disclaimer: The links in this post are not affiliate links; I receive no commission if you choose to purchase through them.”&lt;/em&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Analysing FastAPI Middleware Performance</title>
      <dc:creator>Sergey</dc:creator>
      <pubDate>Mon, 22 Apr 2024 10:34:27 +0000</pubDate>
      <link>https://dev.to/sazonov/analysing-fastapi-middleware-performance-2n61</link>
      <guid>https://dev.to/sazonov/analysing-fastapi-middleware-performance-2n61</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;FastAPI is a well-known and beloved (almost 70k⭐️ on GitHub) modern, fast, asynchronous web framework for building APIs with Python. It is designed for ease of use and high performance, while being robust and production-ready.&lt;/p&gt;

&lt;p&gt;My team quite enjoyed the process of developing apps with FastAPI, finding it a rewarding learning experience. However, one learning was a bit hard: when it came to performance testing, we faced unexpectedly low Requests Per Second (RPS) values, which prompted a deeper investigation, that in turn lead us to learn more about FastAPI Middlewares.&lt;/p&gt;

&lt;p&gt;The purpose of this note is to explore the impact of BaseHTTPMiddleware and ASGIMiddleware on FastAPI application&lt;br&gt;
performance and to share our learnings.&lt;/p&gt;

&lt;p&gt;Spoiler: this is how the performance of real-life production application may change depending on the type of middlewares&lt;br&gt;
we use to implement some common logic:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnngfzxgkyce9mo2scnb2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnngfzxgkyce9mo2scnb2.png" alt="Real-life performance of different middlewares" width="800" height="156"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Background
&lt;/h2&gt;

&lt;p&gt;In FastAPI, middleware plays a crucial role in the request-response lifecycle, acting as a layer that processes requests and responses before they reach the core application logic, or after they leave it. This functionality is pivotal for implementing various features like authentication, data processing, request logging, and error handling.&lt;/p&gt;

&lt;p&gt;Whenever you want to apply some common logic to request processing in more than one endpoint, you might consider using middlewares. FastAPI (more precisely - Starlette on which FastAPI is grounded) offers two types of middleware:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;BaseHTTPMiddleware&lt;/strong&gt;: This type of middleware is designed around a simple and straightforward interface. When using   BaseHTTPMiddleware, you define an async function that takes the request, calls the next item in the middleware chain, and then you can modify the response.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;ASGIMiddleware&lt;/strong&gt;: ASGI (Asynchronous Server Gateway&lt;br&gt;
Interface) &lt;a href="https://asgi.readthedocs.io/en/latest/specs/main.html#middleware"&gt;specification&lt;/a&gt; states:&lt;br&gt;
&lt;code&gt;It is possible to have ASGI “middleware” - code that plays the role of both server and application, taking in a scope and the send/receive awaitable callables, potentially modifying them,and then calling an inner application.&lt;/code&gt; ASGIMiddleware functions within ASGI application, which is a core components of frameworks like FastAPI and Starlette. Moreover, such middleware shares the same &lt;code&gt;coroutine application(scope, receive, send)&lt;/code&gt; signature with ASGI applications. Generally, implementing and supporting ASGIMiddleware is more complex than BaseHTTPMiddleware due to its lower level of abstraction, offering more direct interaction with the ASGI protocol. It's important to note that ASGIMiddleware is not subject to some of the important &lt;a href="https://www.starlette.io/middleware/#limitations"&gt;limitations&lt;/a&gt; of BaseHTTPMiddleware.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As far as middlewares act as a layer in request-response lifecycle, they are expected to have an impact on application performance. The question is - how much? And what is the difference between two types of middlewares supported within FastAPI?&lt;/p&gt;
&lt;h2&gt;
  
  
  The Discovery Process
&lt;/h2&gt;

&lt;p&gt;During performance load testing with ApacheBench (ab) we found that although the application can handle the required RPS it still seems quite low for an async application which does not contain any significant CPU-bound calls. Another point of worry, RPS didn't scale linearly with the number of application instances. We decided to investigate the issue further.&lt;/p&gt;

&lt;p&gt;After intensive research, we came down to reviewing our middlewares and found performance caveats that I will illustrate with experiments below.&lt;/p&gt;
&lt;h2&gt;
  
  
  Experimentation and Analysis
&lt;/h2&gt;

&lt;p&gt;Here are five experiments that nicely represent the investigation process our team went through. I will be running ApacheBench (ab) requests against each experimental case with concurrency 100 to measure RPS of our sample application with different middlewares. I will run each case five times and average the results.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt; ab &lt;span class="nt"&gt;-c&lt;/span&gt; 100 &lt;span class="nt"&gt;-n&lt;/span&gt; 1000 http://127.0.0.1:8000/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Experiment Setup
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Case 0: Baseline (No Middlewares)
&lt;/h4&gt;

&lt;p&gt;Let's start with a simple FastAPI application that contains a single endpoint and no middlewares.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;fastapi&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;FastAPI&lt;/span&gt;

&lt;span class="n"&gt;app&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FastAPI&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;


&lt;span class="nd"&gt;@app.get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;/&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;read_root&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Hello&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;World&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Case 1: Single Simple Middleware
&lt;/h4&gt;

&lt;p&gt;Here are the implementations of both types of middlewares. Both are effectively doing nothing.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# BaseHTTPMiddleware
&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;urllib.request&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;Request&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;starlette.middleware.base&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;BaseHTTPMiddleware&lt;/span&gt;


&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;HTTPMiddleware&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__call__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;call_next&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;call_next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;add_middleware&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;BaseHTTPMiddleware&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dispatch&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nc"&gt;HTTPMiddleware&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;

&lt;span class="c1"&gt;# ASGIMiddleware
&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;starlette.types&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;ASGIApp&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;Send&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;Scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;Receive&lt;/span&gt;


&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ASGIMiddleware&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;ASGIApp&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;app&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;app&lt;/span&gt;

    &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__call__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;receive&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Receive&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;send&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Send&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;app&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;receive&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;send&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;add_middleware&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ASGIMiddleware&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Case 2: Five Stacked Simple Middlewares
&lt;/h4&gt;

&lt;p&gt;Middlewares are still doing nothing, but let's stack them up to find the impact.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# BaseHTTPMiddleware
&lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;add_middleware&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;BaseHTTPMiddleware&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dispatch&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nc"&gt;HTTPMiddleware&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;

&lt;span class="c1"&gt;# ASGIMiddleware
&lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;add_middleware&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ASGIMiddleware&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Case 3: Five Stacked Blocking Middlewares
&lt;/h4&gt;

&lt;p&gt;So far our tests were very synthetic. Let's try to make them more realistic by adding some logic to our middlewares. In asynchronous application it's very important to avoid synchronous calls that block the entire event loop and may have dramatic performance impact, but some blocking calls are unavoidable - like logging (off-topic: offloading logging to a separate thread may help minimize impact).&lt;/p&gt;

&lt;p&gt;Let's add some massive blocking calls to our middlewares.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# BaseHTTPMiddleware
&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;HTTPMiddleware&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__call__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;call_next&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nf"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;/tmp/middleware.log&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;a&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;write&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;HTTPMiddleware&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;call_next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="c1"&gt;# ASGIMiddleware
&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ASGIMiddleware&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;ASGIApp&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;app&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;app&lt;/span&gt;

    &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__call__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;receive&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Receive&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;send&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Send&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nf"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;/tmp/middleware.log&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;a&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;write&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;ASGIMiddleware&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;app&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;receive&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;send&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Case 4: Five Stacked Non-Blocking Middlewares
&lt;/h4&gt;

&lt;p&gt;Let's see whether adding async calls to our middlewares have different impact. Here I'm including an asyncio.sleep for 10ms call to our logic.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# BaseHTTPMiddleware
&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;HTTPMiddleware&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__call__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;call_next&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mf"&gt;0.01&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;call_next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="c1"&gt;# ASGIMiddleware
&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ASGIMiddleware&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;ASGIApp&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;app&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;app&lt;/span&gt;

    &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__call__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;receive&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Receive&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;send&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Send&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mf"&gt;0.01&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;app&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;receive&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;send&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Case 5: Five Stacked Non-Blocking Middlewares with 100ms sleep
&lt;/h4&gt;

&lt;p&gt;Same as previous case but with increased sleep time to 100ms - take it as a representation of a few async database or services discovery calls.&lt;/p&gt;

&lt;h3&gt;
  
  
  Results and Observations
&lt;/h3&gt;

&lt;p&gt;Here is the summary of the results from the experiments above.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3m6i2g3qycfpm765cdxq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3m6i2g3qycfpm765cdxq.png" alt="Summary of middleware test cases" width="800" height="558"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Case 1: Single Simple Middleware (doing nothing)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Impact from adding a single middleware is pretty visible, telling us there is a noticeable overhead of running a middleware.&lt;/li&gt;
&lt;li&gt;BaseHTTPMiddleware is ~15% slower.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Case 2: Five Stacked Simple Middlewares (doing nothing)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The impact of executing five BaseHTTPMiddlewares is significant. RPS drops by an order of magnitude, comparing to Baseline.&lt;/li&gt;
&lt;li&gt;ASGIMiddleware virtually not affected by stacking up.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Case 3: Five Stacked Blocking Middlewares (writing to a file)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Heavy blocking call is not adding much impact to BaseHTTPMiddleware performance, telling us that response time is probably already saturated by middleware overhead.&lt;/li&gt;
&lt;li&gt;Impact on ASGIMiddleware is significant, which is expected.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Case 4: Five Stacked Non-Blocking Middlewares (asyncio.sleep(0.01))&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;BaseHTTPMiddleware with &lt;code&gt;sleep&lt;/code&gt; performs just a tiny bit slower than in case 2 where middleware is doing nothing,      this somewhat supports the idea that we maxed-out middleware overhead impact.&lt;/li&gt;
&lt;li&gt;ASGIMiddleware still faster but to a lesser extent.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Case 5: Five Stacked Non-Blocking Middlewares with 100ms sleep&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Finally, middlewares of different types have gotten on par with each other.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Findings and Recommendations
&lt;/h2&gt;

&lt;p&gt;Based on experiments above BaseHTTPMiddleware has a measurable performance overhead comparing to ASGIMiddleware. The shorter the processing time of a middleware logic, the more significant the difference in performance between the two types of middlewares will be.&lt;/p&gt;

&lt;p&gt;It looks, this overhead comes from &lt;a href="https://anyio.readthedocs.io/en/stable/index.html"&gt;anyio&lt;/a&gt; task management routines used by Starlette to handle middlewares.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/encode/starlette/blob/master/starlette/middleware/base.py#L94"&gt;&lt;strong&gt;BaseHTTPMiddleware&lt;/strong&gt;&lt;/a&gt; class provides a nice and simple abstraction to user. By giving the immediate access to the &lt;code&gt;Request&lt;/code&gt; it makes development and support of middlewares effortless and cost-effective. At the same time, abstraction comes at a cost of overhead (task execution, exception and stream management through anyio library).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ASGIMiddleware&lt;/strong&gt; in turn is way more involving to implement and maintain. Actually it forces you drop down abstraction to the level of ASGI protocol. It steepens the learning curve and raises the requirements to testing and quality assurance, but may bring reasonable performance benefit.&lt;/p&gt;

&lt;p&gt;Here is how a real-life impact of migration from BaseHTTPMiddleware to ASGIMiddleware looks like (optimized middlewares are marked with arrows) - 20%-30% improvement in request processing time in a single endpoint.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3lpro9zjvoazm9y015j2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3lpro9zjvoazm9y015j2.png" alt="Real-life performance of different middlewares with pointers" width="800" height="147"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Even the performance benefit looks impressive, as it happens often - it's a tradeoff with complexity. Unless you heavily relay on multiple stacked middlewares for you business logic, I would not suggest to use ASGIMiddleware before RPS and/or request processing time requirements will force you to. But it's important to keep this option under the belt and use it when other more obvious optimizations opportunities are exhausted.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;FastAPI middlewares are a powerful tool for implementing various features like authentication, CORS handling, logging, adding custom metrics and many more. However, overhead of middleware execution may be significant and should be taken into account while sizing an application. I strongly suggest avoiding the premature optimization and keeping the design as simple as possible which helps to increase Time to Market and reduce maintenance costs. While, if requirements force you to optimize - migrating to ASGIMiddleware might be a good option to consider.&lt;/p&gt;

&lt;h2&gt;
  
  
  References and Further Reading
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;FastAPI documentation on middleware: &lt;a href="https://fastapi.tiangolo.com/tutorial/middleware/"&gt;https://fastapi.tiangolo.com/tutorial/middleware/&lt;/a&gt; and ASGI
Middlewares &lt;a href="https://fastapi.tiangolo.com/advanced/middleware/"&gt;https://fastapi.tiangolo.com/advanced/middleware/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Starlette documentation on middleware: &lt;a href="https://www.starlette.io/middleware/"&gt;https://www.starlette.io/middleware/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Discussion at FastAPI GitHub: &lt;a href="https://github.com/tiangolo/fastapi/issues/2696"&gt;https://github.com/tiangolo/fastapi/issues/2696&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Another experiment on the topic &lt;a href="https://kisspeter.github.io/fastapi-performance-optimization/middleware"&gt;https://kisspeter.github.io/fastapi-performance-optimization/middleware&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  FastAPI #Middleware #Performance #BaseHTTPMiddleware #Python
&lt;/h1&gt;

</description>
    </item>
  </channel>
</rss>
