Skip to content
It Works Locally

Hey Claude, Make No Mistakes

"If the blind lead the blind, both shall fall into a ditch." A story about why good engineers matter.

Buddhika Gamage

· 16 min read

Prologue: The App That Worked

First of all, let me introduce our protagonist: Dilan, a man with big dreams and ideas. One day, while commuting to work, he had an idea: a social app called Yaalu, where you could send short voice notes to circles of friends instead of typing messages. However, he knew nothing about programming. A few days later, he stumbled upon a social media post about a coding agent that claimed it could build better software than the average programmer without prior programming knowledge.

Before you read: this story has six interactive examples, one for each "fix". They run entirely in your browser, so play with them as you go.

On a Friday night, he opened his laptop and installed the latest coding agent. He typed, "Build me this. Make no mistakes."

By Sunday, he had a working app: Next.js on the frontend, a Node.js API, S3 for audio files, and a single PostgreSQL database running on one cloud VM. The agent even wrote a README filled with rocket emojis, which was all the assurance he needed that his app was perfect.

Dilan was over the moon. The app was running smoothly without any issues.

Then, in March, a college influencer posted about Yaalu, and the app went viral. By April, it had 40,000 users. By June, it had 600,000.

By May, Dilan quit his job to focus entirely on the app. As the app grew, so did his ego. Whenever he asked coding agents about his architecture, they called it a great solution and told him he was a great architect. That positive feedback loop sent him straight to cuckoo land. He even updated his LinkedIn profile to read "Founder & CTO of Yaalu."

When a friend who had spent years working as a backend engineer saw the app's potential and offered to review its architecture, Dilan shrugged her off.

"I have multiple AI agents. They don't sleep, they don't ask for equity, and they don't make mistakes. They handle everything across the SDLC, and they do it way better than you guys."

Then came July, the first bump in the road.

The database started to wheeze. Millions of feed entries, reaction rows, and read receipts were piling up in PostgreSQL. Feed loads went from 200 ms to four seconds. The single VM was sitting at 95% CPU usage, and the database disk was filling up with indexes and write-ahead logs faster than the cloud console could add storage.

Dilan opened a new chat. He didn't know why the app was slow, only that it was. But he was confident. So he typed the prompt that started everything:

"The app is slow, and the database can't handle the load. Make it scale like Instagram. Make no mistakes."

The agent replied with several options, starting with the cheapest: move to a bigger machine, add read replicas, and cache the feed. Last on the list was something called sharding, which meant splitting the database into pieces across several servers so that each server stored and served only part of the data.

Dilan had never heard the word "sharding" before. He asked one follow-up question:

"Which one does Instagram use?"

"At their scale, sharding," the agent answered. "But they reached that point after years of growth, with a large infrastructure team. At your size, a bigger machine and a cache will likely buy you a year or more. If you do shard PostgreSQL, use a managed cluster like Citus rather than building your own routing."

Dilan looked up managed sharding, saw the enterprise quote, and winced.

"Bigger machines were for people who didn't think big, and managed middleware was for people who didn't have AI," he thought to himself.

"No paid middlemen. Just spin up four plain database servers and route requests in our API. Keep it clean. Make no mistakes."

Fix 1: Split It by Time

Dilan gave the agent one requirement:

"The feed shows newest posts first. Keep that fast."

He still couldn't have explained what a shard was, so the agent chose the design. And it did exactly what he asked.

It split the posts table into four shards across four new servers, each owning a continuous range of timestamps, with one shard per quarter of the year. Shard 1 held January to March, while Shard 4 held October to December. Inside each shard, posts remained sorted by time.

The benchmark looked beautiful.

"Show me every voice note from March" touched exactly one shard and returned the results in 30 ms.

Dilan was no longer just an ordinary guy. He was the next big tech bro in his country.

He screenshotted the benchmark and posted it on X with the caption:

"Scaled Yaalu to support n number of users in one afternoon. Just me and my macbook 🚀"

Then Monday traffic arrived.

It was the third quarter, so every new voice note, reaction, and comment had a timestamp corresponding to right now. And right now belonged to Shard 3.

Shard 3 hit 98% CPU usage while Shards 1, 2, and 4 idled at 4%, holding old posts that almost nobody read.

He had quadrupled his server bill only to move the same bottleneck to a new address.

Key-range sharding has a well-known trap: when keys arrive in order, like timestamps, every write lands on the same shard. The ranges that made "all of March" cheap also created a hotspot that would move forward one quarter at a time, forever.

Dilan didn't know any of that. He only knew the dashboard was red.

"The load isn't balanced. One shard is dying. Fix it. Make no mistakes this time."

Fix 2: Scramble It with a Hash

The agent proposed hash sharding.

Run each post's ID through a hash function and send it to the shard determined by hash(post_id) % 4. A good hash function scatters keys evenly, regardless of their timestamps.

It also wrote a warning.

Neighbouring keys would now land on different shards, so any query over a range, such as "the newest posts across my circles," would have to query all four shards and merge the results.

Since users belonged to multiple overlapping circles, the agent suggested a compound key instead: hash circle_id or user_id to group related posts on the same shard, and keep them sorted by time inside that shard. This would trade a bit of write fan-out for faster single-shard reads.

Dilan read the first sentence and the last line of code.

"Evenly" was all he needed.

The feed got slower anyway.

Every feed load now fanned out to all four shards, waited for every response, and then merged and sorted the results. Each request was only as fast as its slowest shard.

When one shard paused for vacuuming, every user's feed paused with it.

Dilan had the agent put Redis in front of the feed timeline, and the graphs stayed green for a few weeks.

Try it

Where does a voice note live?

It's a Monday in August. Switch the sharding strategy and watch which shards do the work.

Shard key

Write load: Monday, 400 new voice notes

Shard 14% CPU
Shard 24% CPU
Shard 398% CPU
Shard 44% CPU

“Every voice note from March”

S1S2S3S41 shard

“Newest posts across my 3 circles”

S1S2S3S41 shard

Every write is stamped "now", and now lives on one shard. The other three hold old posts nobody reads.

The Anomaly

In September, a famous singer joined Yaalu and posted a 40-second voice note. It received 2.1 million reactions in a single day.

Every one of those reactions was a write to the same counter row: post:9917.

Hashing spreads different keys. It can't do anything when everyone wants the same one.

All 2.1 million writes were hashed to Shard 2. Shard 2 went down, and with it, a quarter of every user's feed.

"One post is killing an entire shard. Fix it. No mistakes."

The agent explained salting.

You add a suffix to the hot key, so post:9917 becomes post:9917_00 through post:9917_99, and each reaction picks a suffix at random. That spreads the writes across all four shards.

It also spelled out the price: to read the reaction count, you now have to fetch all 100 pieces across the shards and add them together. You should also salt only the keys you know are hot, which means tracking which ones are.

The writes recovered.

But opening a viral post's page, which bypassed the feed cache to show live reactions, now triggered 100 database reads instead of one.

The post page crawled.

Annoyed that his old chat was getting sluggish because of its massive context window, Dilan opened a fresh session, pasted only the slow read endpoint, and typed:

"Why is this looping 100 times just to read one reaction count? Make it one query and cache it."

Without the write path in its context, the new agent saw what looked like absurdly redundant code. It stripped the loop down to a query for only the base bucket, post:9917_00, and cached that number.

Nobody reviewed the diff because Yaalu had nobody who could.

The next morning, the singer's fans were sharing screenshots.

Her post, which had 2.1 million reactions, showed just 21,384. That was fewer than a rival influencer's.

Her manager tweeted that Yaalu was "suppressing" her, and that tweet received more reactions than the voice note itself.

Try it

One post, 2.1 million reactions

Salt the hot counter into buckets, then try the one-line “optimisation” from the fresh chat.

Counter keys
Reaction count reader

Writes per shard · keys post:9917

Shard 10
Shard 2DOWN
Shard 30
Shard 40

2,100,000

reactions shown on the singer's post

1

database read per page view (before caching)

Fix 3: Just Add One More Server

Dilan pasted both files back into one chat, got the count bug patched, and hard-coded the hot-key list with one entry: the singer.

Growth kept coming. By October, Yaalu had 1.4 million users.

All four shards were now busy, so Dilan did the obvious thing.

"Add a fifth shard. Zero downtime. No mistakes."

The agent flagged the problem in its first line.

The data was placed using hash % 4. Changing that to hash % 5 would give four out of every five keys a different remainder. In other words, moving from four nodes to five would relocate 80% of all posts to a different machine.

The right fix was to create far more logical shards than physical servers upfront. For example, create 1,024 logical schemas spread across four machines. Then, when adding a new server, you could simply move entire logical shards from the existing machines without changing the hash function.

The agent offered to restructure the system first.

"How long?" Dilan asked.

"A careful migration, with dual writes and verification: about a week."

"We're doing it tonight."

So the agent wrote a background migration script that rehashed rows using % 5 and started copying them across servers, while simultaneously updating the API to use % 5.

It ran on a Saturday night, which happened to be when Yaalu's traffic peaked.

The API switched to % 5 the moment the script started. The data, however, would take hours to arrive.

For most of that time, a request for a post went to the shard where the post should exist under the new routing rule, only to find nothing.

Worse, the copy traffic saturated the private network between the VMs. That made the copying process even slower, which kept the migration window open for longer.

By midnight, #YaaluDeletedMyVoiceNotes was trending, and users were posting screen recordings of their empty profiles.

A woman wrote that the last voice note from her late grandmother was gone.

Actually, it wasn't.

Her grandmother's audio file was still safe in S3, and its database record was sitting untouched on Shard 1 while the API looked on Shard 4.

But Dilan couldn't tell her that with any confidence because, by then, he didn't know where anything was.

Try it

Adding one more server

Each square is a voice note. Change the number of servers and see how many notes have to move.

Placement

moves to another machinestays put

80%

of all posts must be copied

Every key is re-divided by 5.

Fix 4: Roll It Back (Halfway)

At 1 a.m., Dilan killed the copy script and typed:

"Roll back to four shards. Now."

The agent changed SHARD_COUNT=5 back to 4 in the configuration and started a rolling deployment across Yaalu's 12 API servers.

That was the moment Dilan learned that his shard map didn't live anywhere central. Each API server had its own copy, baked into its environment variables.

The rollout stalled at Server 7 when a container pull timed out and failed its health check.

For the next 40 minutes, six servers routed requests using % 4, while the other six used % 5.

A user who recorded a voice note could be sent, at random, to one of two different routing rules.

A post written through Server 3 went to Shard 2. A refresh through Server 9 looked for it on Shard 4.

People reposted the notes they thought were lost, so notes that weren't lost now existed twice. Some replies were saved on one shard while the posts they answered were on another, leaving orphaned threads everywhere.

The agent explained what was missing.

Every part of a custom-routed system has to agree on which shard lives where, especially while shards are moving.

Real systems keep one authoritative shard map in a coordination service such as ZooKeeper or etcd. Routers subscribe to that map so they can all switch together.

Underneath, the agent added, that agreement is a consensus problem, which is why those services run as odd-numbered clusters of three or five nodes.

"Add etcd. Keep it simple. One small server is fine."

The agent set up a single etcd node, and the API servers cached the map in memory for 10 minutes.

Over the next week, they cleaned up the split writes and finally finished moving to five shards through etcd.

It worked until the single etcd VM rebooted for an unattended kernel patch on a Tuesday afternoon.

When the API servers' 10-minute caches expired during the reboot, they couldn't reach etcd, so they fell back to the hard-coded default in the Node.js router.

The default, left over from July, was SHARD_COUNT=4.

Half the cluster spent the next 10 minutes writing to the wrong shards all over again.

That night, Dilan's co-founder, who handled marketing, sent him a message:

"Are we sure we don't need an actual engineer?"

Dilan replied:

"The AI just needs better prompts."

Try it

Twelve servers, two opinions

Roll back some servers to % 4, then record voice notes. The write and the refresh each hit a random API server.

%4%4%4%4%4%4%5%5%5%5%5%5

40%

of refreshes can’t find a note that exists

Last attempts

Nothing recorded yet.

Fix 5: Make Search Fast

By November, the users table had been sharded by user_id too.

Looking up a user by ID was instant because the ID told the system which shard to query.

But nobody searches by ID.

People search by handle, like @nethmi, and by hashtag.

The agent had given each shard a local index covering only the rows on that shard.

A search for @nethmi couldn't know which shard she was on, so it queried all five, waited for all five responses, and merged the results.

At peak times, search took 2.8 seconds because the slowest shard set the pace.

"Search is slow. Make it instant. No mistakes."

The agent laid out the trade-off plainly: you choose which side is slow.

A local index gives you fast single-shard writes and slow scatter/gather reads.

A global secondary index, which acts as a lookup table for every handle and is itself sharded by the first letters of the handle, gives you fast single-shard reads.

Because keeping two different shards strictly in sync on every signup requires slow distributed two-phase commits, global indexes are usually updated asynchronously through a background queue. This means they can be briefly stale.

The agent added an explicit comment in the code:

"Do not use this index to enforce unique handles at signup."

Dilan watched search times drop from 2.8 seconds to 40 ms.

Two weeks later, while prompting another agent to speed up the onboarding flow, he told it to replace the slow five-shard uniqueness check on the signup form with the fast global index.

On a busy Friday evening, the background queue backed up, and the global index fell 90 seconds behind.

Within that 90-second window, each user's random user_id landed on a different shard, so no local UNIQUE constraint caught the duplicates either.

Two people registered @nethmi.

Three registered @yaalu_support.

And someone registered the singer's exact old handle, seconds after she changed it during a verified-account rebrand, before the redirect reservation had propagated.

The impersonator posted a voice note cloned from her old interviews. It asked fans to donate to an emergency flood-relief fund and included a bank account number.

Yaalu's own search pointed people straight to the fake account.

By the time Dilan understood what had happened, 3.2 million rupees had been wired.

Try it

Two people want @nethmi

Pick how the signup form checks that a handle is free, then move the second signup closer to the first.

Uniqueness check

Two @nethmi

Both accounts exist. Search can point at either.

40 ms

Fast, but it only knows about a handle once the background queue catches up.

Fix 6: Make It Heal Itself

By December, Yaalu had finally migrated to 1,024 logical PostgreSQL schemas spread across the five database VMs and routed through etcd.

But Dilan was exhausted from waking up at 3 a.m. whenever a node ran hot.

So he wrote his most ambitious prompt yet:

"I want the cluster to manage itself. Build a daemon that watches the five nodes. If a node fails, move its logical shards to the others automatically. And when a dead node comes back online, wipe it clean so it can take shards back without stale data conflicts. Zero humans in the loop. Make no mistakes."

The agent built the daemon, but it warned him one last time.

Fully automatic rebalancing is notoriously dangerous.

A node that is merely overloaded can miss health checks and appear dead. Moving hundreds of gigabytes off it creates heavy network and disk loads on neighbouring nodes that are already near capacity, potentially triggering cascading failures.

Most production systems require a human to approve shard moves and rely on hot standby replicas for failover rather than copying data across active primaries.

None of Yaalu's five database nodes had a standby replica. Back in August, Dilan had skipped them to keep his cloud bill down.

Dilan replied with a thumbs-up emoji, deployed the daemon, and went to sleep.

New Year's Eve

At 11:58 p.m. on 31 December, 1.9 million people opened Yaalu simultaneously to send a "Happy New Year" voice note to their circles.

Node 3 was the first to choke.

Checkpointing stalled its disk I/O, and it took six seconds to respond to a health check with a five-second timeout.

The daemon declared Node 3 dead, even though it held the only copy of Shards 400 through 600, and kicked off pg_dump streams over SSH to pull its data onto Nodes 1, 2, 4, and 5 before shutting it down.

Those four nodes were already running at 90% CPU while serving midnight traffic.

Now they were also ingesting 400 GB of live migration streams and rebuilding indexes.

Node 5 missed a health check next, so the daemon declared it dead too and started evacuating its shards onto the surviving nodes.

Node 1 went two minutes later.

By 12:07 a.m., the cluster had declared three of its five nodes dead.

None of them had actually crashed.

They were drowning in each other's rescue traffic.

Then, at 12:09 a.m., Node 3's disk queue cleared while half its shards were still waiting in the transfer queue.

Its heartbeat succeeded, and it registered as "recovered."

The rejoin script Dilan had asked for did exactly what its prompt specified.

To prevent split-brain conflicts from a returning node, it immediately initialized a clean PostgreSQL data directory, wiping every uncopied shard from Node 3's disk so it could start accepting fresh assignments.

Because Node 3 had no replica, every row in those uncopied shards existed nowhere else.

Panicking at 12:20 a.m., Dilan opened the backup bucket.

The nightly pg_dump cron job had reported green checkmarks every single night since July.

Nobody had ever updated its connection string after Fix 1.

For five months, it had faithfully backed up the original standalone VM from the summer, an empty database that hadn't received a single write since August.

The raw audio files were still sitting in S3: millions of unlabeled UUIDs like 8f3a-991c, with no metadata left to tell anyone who recorded them, when they were sent, or which circle they belonged to.

One in every six voice notes posted since August, including wedding toasts, birthday songs, a father's nightly notes to his son, and the grandmother's last message, had become nameless static in an S3 bucket.

Try it

Midnight, five nodes, no replicas

Choose a failure policy and a night, then press play. One step is one minute.

When a health check fails
Traffic
11:58 pm

Load (health check times out above 100%)

Node 186%

healthy · 205 shards

Node 280%

healthy · 205 shards

Node 3102%

healthy · 205 shards

Node 478%

healthy · 205 shards

Node 588%

healthy · 204 shards

0.0%

of all data gone forever (0 shards)

0.0%

of shards unreachable right now

Daemon log

Waiting for midnight.

Point of No Return

On 2 January, Dilan finally called the backend engineer friend he'd laughed at in June.

"I can stabilise the cluster and try to match some orphaned audio files using S3 access logs," she said quietly after spending two hours looking through his servers.

"I can't reconstruct the social graph for those wiped shards. Nobody can."

The App Store rating fell from 4.8 to 1.9 in a week.

Daily active users halved, then halved again.

The seed investor who had sent a term sheet in December wrote a polite email saying they would "revisit in a later quarter."

Yaalu had survived going from zero to almost two million users in nine months.

It had survived viral traffic, overloaded databases, hot shards, failed migrations, inconsistent routing, and a cluster that nearly destroyed itself.

But it couldn't survive its founder's refusal to listen.

Dilan had spent nine months telling machines to make no mistakes.

He had never once asked himself whether he knew enough to recognise one.

“The fool who knows his foolishness is wise at least to that extent. But the fool who thinks himself wise is a fool indeed.”

The Dhammapada, Verse 63

  • sharding
  • postgresql
  • distributed-systems
  • system-design
  • ai-agents

Discussion

You’ll get a random name

No account needed, your comment gets a random name. Or sign in / register to keep your name reserved.

Loading comments…

    1. Engineering

      Causality in collaborative editors, part 2

      Yjs Internals: Origins, YATA and State Vectors

      How Yjs orders concurrent edits without trusting a single clock: item origins, the YATA tie-break, state vectors, the sync handshake and the rules you have to respect in production.

      12 min read

    2. Engineering

      Causality in collaborative editors, part 1

      No Effect Before Its Cause: From Einstein to Lamport

      Einstein's moving train, Leslie Lamport's clocks and a 2,500-year-old idea explain the core problem of leaderless replication: ordering writes when no clock can be trusted.

      14 min read

    3. Books

      Timshel: The One Word That Explains Your Entire Life

      On John Steinbeck's East of Eden and the meaning of 'Timshel': the idea that what makes us human is the power to choose.

      6 min read

    Newsletter

    Read the next one first.

    New posts in your inbox, about every two weeks. No spam, unsubscribe in one click.