Reading this online? Press R, or use the button
in the corner, to show the narration that goes with each slide.
Hello — I'm Tay
Abdulmateen Tairu @taycode
Software Engineer at Chatarmin
I've spent my career building
event-driven and data-intensive systems — fintech, AI data
pipelines, logistics, and now messaging at scale.
F1 and football, roughly in that order.
Where these examples come from
Web activity pipeline — scraping and classifying pages
Savings fintech — 3,000 → 30,000 users · ~₦1bn a year
ETL pipelines — Airflow, millions of rows, 2½ years
Unified inbox SaaS — millions of messages, B2B and B2C,
Germany and Austria
Not Google scale.
Thirty thousand users.
What "data-intensive" means
Your bottleneck is the data, not the logic.
Not how much does this compute? — but
how much data, arriving how fast, shaped how awkwardly.
Seven examples, each one teaching one idea:
1
A loop over 3,000 accounts
Job granularity
2
Work that never left the web server
Decoupling the request cycle
3
Two servers, one cron job
Idempotency
4
Everyone retrying at once
Backoff & circuit breakers
5
A balance that went negative
Atomicity & transactions
6
Backfilling 100,000 rows live
Batching & pagination
7
Events we couldn't name
Observability
Starting with number one — a loop over three thousand accounts.
§2 Processing workloads · The situation
Debiting 3,000 accounts at midnight
A savings product. Every midnight, we move money for everyone
who set up a mandate.
@cron("0 0 * * *")
def process_mandates():
mandates = Mandate.objects.filter(active=True) # 3,000 rows in memory
results = []
for mandate in mandates:
results.append(debit_customer(mandate)) # a network call, each time
send_summary(results)
Blast radius — #412 raises, and #413 to #3,000 never run
Retries are all-or-nothing — re-running debits whoever already paid
Memory grows with the data — every row, every result, held all night
No visibility — one log line for 3,000 financial operations
§2 Processing workloads · What we did & the concept
One job per mandate
@cron("0 0 * * *")
def enqueue_mandates():
ids = Mandate.objects.filter(active=True).values_list("id", flat=True)
for mandate_id in ids:
process_mandate.delay(mandate_id) # 3,000 independent jobs
@celery.task(bind=True, max_retries=3, autoretry_for=(ProviderError,))
def process_mandate(self, mandate_id):
debit_customer(Mandate.objects.get(id=mandate_id))
Whatever you made a unit of work is the only thing you can
retry, observe, or scale.
Unit = the whole night
Unit = one mandate
one failure stops everything
one failure stops one customer
retry the whole batch
retry that one job
memory = all rows
memory = one row
one log line
a job id and status per customer
That was work trapped inside a loop. The next one had already been moved off the request — or so we thought.
§2 Processing workloads · The situation
The work was a workflow, not a job
Company A: 50,000 raw support conversations,
to be cleaned and labelled for training.
step 1 ingest the client's export millions of rows
step 2 strip names, emails, card numbers slow, and must not fail quietly
step 3 auto-label with a model expensive
step 4 send the unsure ones to reviewers humans, so: hours or days
step 5 package it and hand it back big files, cloud storage
Every client has a different sequence.
The sequence is the product.
The gateway's call now returns in milliseconds, so it stops mattering how
fast it drains Kafka. And the callback comes from the worker that actually did
the work — the only thing that knows when it's really finished.
§2 Processing workloads · What we did next
Not every step costs the same
Stripping PII takes a second. Labelling takes minutes.
One queue, and the quick job waits behind the slow one.
celery_app.conf.task_routes = {
"tasks.label_conversations": {"queue": "heavy"}, # CPU-bound, minutes
"tasks.package_dataset": {"queue": "heavy"}, # big files, lots of memory
"tasks.strip_pii": {"queue": "light"}, # quick, high volume
"tasks.notify_client": {"queue": "light"},
}
queue: heavy ──▶ a few large instances celery -Q heavy -c 4
queue: light ──▶ many small, shared ones celery -Q light -c 20
Two pools, scaled independently — a labelling backlog
adds heavy workers and touches nothing else.
§2 Processing workloads · The concept
Getting work out of the request path
Moving work out of a request needs five things.
BackgroundTasks gives you one of them.
BackgroundTasks
Worker + queue
Fast response
yes
yes
Separate process
no
yes
Bounded concurrency
no
yes
Automatic retries
no
yes
Survives a restart
no
yes
And two things it took us an outage to learn:
a queue only protects the hop it sits in front of — ours was two hops
upstream — and work of different weights needs different queues,
or the one-second job waits behind the twenty-minute one.
Both of those are about where work runs. The last one is about what decides when it runs.
§2 Processing workloads · Before & after
An export that lived on someone's laptop
Before
every day, at a set time
│
┌──────────┐
│ a person │ runs a script
└──────────┘ │
▼
┌──────────┐
│ laptop │──▶ cloud
└──────────┘
"Run these steps in order, on a schedule, and let me re-run step 4"
Orchestrator Airflow, Prefect, Dagster
"Route messages to workers, each one consumed once"
Broker RabbitMQ, SQS
"Many consumers on the same stream, replay from last Tuesday"
Log Kafka
"I have Postgres and thirty thousand users"
A table FOR UPDATE SKIP LOCKED
Most of the pain I've seen came from bending one into another — building
dependency graphs out of Celery chains, or running Kafka where a table would do.
Everything so far pushes work off the critical path — into queues, workers, schedulers. Which means it now runs somewhere you are not watching. And sometimes it runs twice.
§3 Reliability · The situation & what broke
We added a second server
BEFORE AFTER
┌───────────┐ ┌───────────┐ ┌───────────┐
│ server │ │ server │ │ server │
│ + cron │ │ + cron │ │ + cron │
└───────────┘ └───────────┘ └───────────┘
│ │ │
midnight midnight midnight
1 debit 1 debit + 1 debit
Same savings product, more load. We scaled the way everyone scales — and
the deploy image carried the cron with it.
Money left accounts twice in one night
One balance went negative, past a check that was
supposed to make that impossible
We found out because a customer told us
§3 Reliability · Why it broke
Why the same work runs twice
Queues guarantee at least once — not exactly once.
The gap shows up at failure boundaries:
A retry after a timeout — it went through, you never heard back
← the common one
A worker dies before it acknowledges — the broker re-delivers
A webhook is redelivered — WhatsApp, Instagram, Stripe all document this
Two schedulers fire the same job← what happened to us
The client sends it twice — a double-click, or its own retry
Most days none of this happens. That's the trap —
"most days" isn't a guarantee, and here it is somebody's money.
§3 Reliability · What people try first
Three ways to stop two runners colliding
Two servers woke up. How do you stop the second one?
1 · Take a lock— pessimistic
with redis.lock("cron:mandates"): # only one server gets in
process_mandates()
Stall past the lock's timeout and it expires while you're still working.
2 · Check a version— optimistic
UPDATE mandates SET status='running' WHERE id=42 AND version=7;
-- 0 rows updated = someone beat you to it
Protects the row. Not the debit you already sent the provider.
3 · Split the work— partitioning
if ring.owner(mandate_id) == this_node: # each node owns a slice
process(mandate_id)
Ownership moves when a node joins or leaves.
All three make a second run less likely.
None of them makes a second run safe.
§3 Reliability · The idea
So stop trying to prevent it
You just saw three ways to stop the second run. All three leak.
So don't stop it — make it not matter.
press a lift button 5 times the lift still comes once
switch a light off 5 times it's still off
add ₦100 to a wallet 5 times you have ₦500
The first two you can repeat without thinking. The third you cannot.
That property has a name: idempotent.
Idempotent — an operation you can run any number of times and
still get the result of running it once.
This is the shift: you stop trying to guarantee the work happens
exactly once, and instead make it safe for the work to happen
more than once — which is achievable, and the other one isn't.
§3 Reliability · Why it matters
What a second run actually costs
THE OPERATION RUN IT TWICE
─────────────────────────────────────────────────────────
SET status = 'paid' nothing changes
balance = balance - 4,200 debited twice
send_sms("₦4,200 debited") told twice
INSERT INTO payouts (...) paid twice
Only the first line is safe to repeat. It sets a value.
The rest apply a change — and a change applied twice is a different
number, a confused customer, or money out the door.
A payment provider sends payment.succeeded. The network blips and it
redelivers — which is documented behaviour, not a bug.
We credit the wallet twice, and we were paid once.
Nothing in our code was wrong. We just had no way to say
"I have already seen this one."
§3 Reliability · What we did
Let the database refuse the second one
Both crons still fire at midnight. Only one of them debits anybody.
CREATE UNIQUE INDEX ON mandate_runs (mandate_id, run_date);
@celery.task(bind=True, max_retries=3)
def process_mandate(self, mandate_id, run_date):
try:
with db.begin():
db.add(MandateRun(mandate_id=mandate_id, run_date=run_date))
except IntegrityError:
return "already processed" # the second server stops here
debit_customer(mandate_id)
00:00 server A inserts (918, 2026-08-21) ──▶ debits
00:00 server B IntegrityError ──▶ stops
Two servers, ten servers, or a replay three days later —
the row can only exist once, so the debit can only happen once.
§3 Reliability · The concept
Where the key comes from
Most work is not naturally repeatable. You make it repeatable by giving each unit of work a key the database remembers.
key = str(uuid4()) # new key every attempt — useless
key = f"{mandate_id}:{run_date}" # same key every attempt
Derive the key from the work, not from the attempt.
Good keys
mandate_id + run_date
order_id
the provider's message id
Bad keys
anything with a timestamp
a fresh UUID
the hostname or retry count
Where you can, rewrite the work so it sets a value instead of
applying a change — an upsert, a delete by id, SET status = 'paid'.
Then the key stops being the only thing standing between you and a double charge.
§3 Reliability · The situation & what broke
A pipeline leaning on somebody else's API
A URL enrichment pipeline. Every job calls a third-party
API. One afternoon it got slow — not down, just slow.
for attempt in range(5):
try:
return classify(url)
except Exception:
time.sleep(1) # wait exactly one second, then try again
t+0s the API slows down
t+1s every worker retries at the same instant ──▶ more load, slower still
t+2s every worker retries at the same instant ──▶ it starts returning errors
t+3s every worker retries at the same instant ──▶ ...
Same fixed second, so every client comes back together.
And each worker sits blocked in sleep — our own queue backs up too.
Circuit breaker — once you know it's down, stop calling.
Fail fast, or route elsewhere.
Timeouts on every network call — requests defaults
to none. One hung socket holds a worker forever.
A queue per dependency — a stuck SMS provider must not stop
payments.
§3 Reliability · Designing for it
An open circuit is a chance to go elsewhere
def charge(amount, ref):
for provider in PROVIDERS: # primary, then fallback
if breaker.is_open(provider.name):
continue # known down — skip it
result = provider.charge(amount, ref)
record(ref, provider=provider.name, external_id=result.id)
return result
raise AllProvidersDown
Only works if you built for it before the outage:
One interface, many adapters — no
if provider == "x" in business logic
Normalise on the way back in — they won't agree on what
"pending" means
Record who processed what — their name, and their
reference id
Point 3 isn't bookkeeping — refunds and disputes go back to whoever moved the money.
Your idempotency key stays yours.
Retries, replays, failovers — every one of them means the same work reaching your data more than once. So the data has to survive it.
Read the balance. Check it. Debit. Four lines, reviewed, tested, obviously correct.
Balances went negative anyway.
And not always by accident — people worked out they could fire two
requests at the same moment and withdraw more than they had. In a financial system,
concurrency is an attack surface.
§4 Databases · Why it broke
The check was correct. It wasn't atomic.
request A request B
───────── ─────────
read balance 5,000
read balance 5,000
check 5,000 >= 4,200 ok
check 5,000 >= 4,200 ok
balance = balance - 4,200 800
balance = balance - 4,200 −3,400
Between the read and the write, someone else read the same number.
Both requests were individually correct — and ₦8,400 left an
account holding ₦5,000.
This is a race condition: the result depends on the order two
things happen to interleave.
§4 Databases · What we did
Make the check and the write one operation
-- check and write in a single statement
UPDATE accounts SET balance = balance - :amt
WHERE id = :uid AND balance >= :amt; -- 0 rows updated = declined
# or hold the row while you decide
acct = db.query(Account).filter_by(id=uid).with_for_update().one()
-- and a backstop the application cannot forget
ALTER TABLE accounts ADD CONSTRAINT bal_nonneg CHECK (balance >= 0);
The single statement is the right default. The constraint costs nothing
and saves you when someone adds a new code path next year.
§4 Databases · A different system
What belongs inside a transaction
Another fintech: every withdrawal sends an SMS.
We saw both halves fail, separately.
Locked for someone else's outage
with db.begin():
order.status = "paid"
provider.charge(...) # 200ms… or 30s
send_email(...)
Locked for microseconds
with db.begin():
order.status = "paid"
db.add(Outbox(
topic="order.paid",
payload={"id": order.id}))
Never hold a lock across a network call you don't control.
But take it out and the two can now disagree.
Writing the intent in the same transaction is the outbox.
§4 Databases · The concept
Why the outbox works, and who drains it
commit succeeds ──▶ process dies ──▶ the SMS is never sent
SMS sent ──▶ commit rolls back ──▶ you told them about money
that never moved
Put the intent in the same transaction as the change and
those two can never disagree. Delivery becomes a separate problem, with its own retries.
A cron that flushes it
SELECT id, topic, payload FROM outbox
WHERE published_at IS NULL
ORDER BY id LIMIT 100
FOR UPDATE SKIP LOCKED;
for row in batch:
broker.publish(row.topic, row.payload)
mark_published(row.id)
Every few seconds. No new infrastructure.
SKIP LOCKED lets several run at once.
Tails the replication log instead of polling. Lower latency, no
query load — and one more system to operate.
Publish, then mark. A crash in between duplicates an event rather
than losing one — and duplicates you already handle.
Not a trigger: a trigger runs inside your transaction and can't
safely make a network call.
§4 Databases · The situation
Moving 100,000 rows on a live product
A creatives marketplace. New workspace model,
100,000 rows to rebuild, product live throughout.
-- migrations/0042_workspace_v2.sql workspaces: 100,000 rows
ALTER TABLE workspaces ADD COLUMN owner_id bigint; -- instant
UPDATE workspaces SET owner_id = legacy_owner; -- locks every row,
-- in one transaction
ALTER TABLE workspaces ALTER COLUMN owner_id SET NOT NULL; -- full table scan,
-- blocks reads AND writes
CREATE UNIQUE INDEX ON workspaces (slug); -- blocks writes for
-- the whole build
Four ordinary lines. One is instant. The other three hold your
production database while the deploy waits.
§4 Databases · Why it breaks things
A slow migration doesn't just run slowly
It's one transaction — rows stay locked until the whole
migration commits, not until that statement finishes
Some of it blocks readers too — SET NOT NULL takes
ACCESS EXCLUSIVE: no writes, no reads
Locks queue — and that's the real killer. You wait behind a long
query; everything else waits behind you
SET lock_timeout = '3s'; -- fail fast instead of building a queue behind you
Migrations change structure, and should be quick.
Moving data is a separate job — batched, pausable, resumable.
§4 Databases · What we did
A backfill script, run in batches
last_id = load_checkpoint() # resumable
while True:
rows = (db.query(Old).filter(Old.id > last_id) # keyset, not OFFSET
.order_by(Old.id).limit(1000).all()) # bounded memory
if not rows:
break
with db.begin(): # short transaction
db.execute(insert(New), [map_row(r) for r in rows])
last_id = rows[-1].id
save_checkpoint(last_id) # safe to restart
log.info("backfill.progress", extra={"last_id": last_id})
time.sleep(0.1) # leave room for users
Why id > last_id, not OFFSET:OFFSET 90000 makes Postgres fetch and discard 90,000 rows to hand you
1,000. Keyset paging is an index seek — batch 900 costs what batch 1 did.
A dozen lines, and every one of them is a pattern from earlier in this talk.
Queues, keys, locks, batches — every one of them is invisible until something measures it.
§5 Observability · The situation & what it cost
An event system made of database triggers
A logistics product. No message bus — cloud functions watched the
database and guessed what had happened by diffing snapshots.
a row changes ──▶ a function wakes up ──▶ diff old vs new
──▶ guess what happened
──▶ decide what to do next
Couldn't track anything — there was no "booking confirmed",
only a row that used to look different
Couldn't retry anything — nothing to replay. The reaction was
lost, quietly
Couldn't add anything safely — a new feature meant another
function diffing the same rows
§5 Observability · What we should have done
Name the event. Publish it. Consume it.
booking confirmed
│
▼
┌───────────────────┐
│ booking.confirmed │ ← an event, with a name
└───────────────────┘
│
┌─────────┼─────────┬──────────┐
▼ ▼ ▼ ▼
notify invoice analytics audit log
Easier to track — the name is searchable, countable, alertable
Easier to retry — the event is a record, so replay it
Easier to build — a new feature is just a new consumer
Easier to follow — give it an id, carry the id everywhere,
and one booking is traceable end to end
§5 Observability · What we couldn't see
"The dashboard says it's fine"
A customer says the app is slow. The dashboard says
80ms average. Green everywhere.
You are both telling the truth.
1,000 requests
999 took 50 ms
1 took 30 s
─────────────────────
mean 80 ms ← what the dashboard showed you
The average is real. It just describes a request that never happened
to anybody.
§5 Observability · The concept
Why the slow 1% isn't 1% of your users
Line every request up from fastest to slowest:
p50 the middle one — half your requests were faster
p99 99 out of 100 were faster than this
p99.9 999 out of 1,000 were faster than this
Now: one page load in your app makes 30 API calls.
For that page to feel fast, all 30 have to land in the quick 99%.
0.99 ^ 30 = 0.74
→ 26% of page loads hit the slow path.
→ roughly 1 in 4.
p99 is not your unluckiest customer. It is a quarter of your traffic.
Alert on it.
§5 Observability · What to watch
Four things worth instrumenting
Queue depth & oldest-message age — the earliest signal.
Latency alerts fire minutes later
p99 per endpoint — a global p99 hides one bad route
Retry & failure rate per dependency — rising retries mean a
breaker is about to matter
Slow queries by total time, not average — 100k × 20ms
beats the 2-second one you're staring at
And whatever must never be true — alert on it.SELECT count(*) FROM accounts WHERE balance < 0 should be a monitor,
not a phone call.
Seven examples, seven ideas
A loop over 3,000 accounts
Granularity is what you can retry and see
Work that never left the web server
A fast response isn't moved work
Two servers, one cron
Assume it runs twice — key it, index it
Everyone retrying at once
Backoff with jitter, then stop calling
A balance that went negative
Check and write in one operation
100,000 rows on a live product
Batch it, make it resumable
Events we couldn't name
Name it, trace it, alert on p99
None of these were exotic failures. Every one
of them was ordinary code that had been working, meeting more data than it was
written for.
Thank you
Abdulmateen Tairu @taycode Software Engineer at Chatarmin