Home›Design›Anti-patterns
Designs · what not to put where

Anti-patterns

Which database habits look harmless and turn into incidents?

You will learn: fifteen placement and modeling mistakes, the symptom each one causes, why it happens inside the engine, and what to do instead.

Most of these work fine in development and fail only under real traffic or real data size. That is why they survive code review. Where a notebook measured the effect, the card links to it.

Read the value, then write the new value

PROBLEMINSTEADstock: 1A reads 1B reads 1both write 0: 2 sold, 1 in stockavailable - 1WHERE available >= 1second sale:0 rows updated
What you see
Stock goes negative, or two deposits become one, only under load.
Why it happens
Two sessions read the same old value and each writes its own result. The second write wins.
Do this instead
Write relative to the current value with a condition: UPDATE stock SET available = available - 1 WHERE sku = $1 AND available >= 1. Measured in Notebook 6.

A counter on one hot row

PROBLEMINSTEADcounterevery writer waits for one row lock+1+1+1Redis INCR, orseveral rows, summedno single hot row
What you see
Lock waits on one row. The pool runs out during a spike.
Why it happens
Every increment must wait for the previous one to commit, so a single row serializes all writers.
Do this instead
Count in Redis and flush totals in batches, or spread the counter over several rows and sum them. Design doc.

A queue table polled by several workers

PROBLEMINSTEADworkerworkerworkerjob 1all three pick the same rowworkerjob 1workerjob 2workerjob 3FOR UPDATE SKIP LOCKED
What you see
Workers process the same job twice, or wait on each other's locks.
Why it happens
Each worker selects the oldest job, and they all pick the same row.
Do this instead
SELECT ... FOR UPDATE SKIP LOCKED (PostgreSQL 9.5 and later, MySQL 8.0 and later) so each worker takes a different row. At high rates, use a real queue.

Random UUIDs as the InnoDB primary key

PROBLEMINSTEAD+++new rows land on random pagesall over the table+bigint or UUIDv7:new rows go to the end
What you see
Inserts slow down as the table grows. The buffer pool never seems big enough.
Why it happens
InnoDB stores rows in primary key order. Random keys land on random pages, so inserts dirty pages all over the table, and every secondary index carries the 16-byte key too.
Do this instead
Use a bigint identity, or a time-ordered UUID (version 7), so new rows go to the end. How InnoDB stores rows.

OFFSET paging deep into a list

PROBLEMINSTEAD500,000 rows read and thrown away20OFFSET 500000 LIMIT 20jump by keyWHERE id > last_id
What you see
Page 1 is fast, page 25,000 times out.
Why it happens
OFFSET reads every skipped row and throws it away.
Do this instead
Page by key: WHERE id > last_seen ORDER BY id LIMIT 20. Measured in Notebook 5.

A transaction open across a network call or a user's think time

PROBLEMINSTEADone transaction, open for an hourdead row versions pile upVACUUM or purge cannot remove themshort transactionscleanup keeps upslow work outside it
What you see
Tables bloat, undo grows, VACUUM or purge falls behind.
Why it happens
The open snapshot forces the database to keep every old row version it might still need.
Do this instead
Do the slow work outside the transaction, then open it, write, and commit. Set idle_in_transaction_session_timeout in PostgreSQL. Measured in Notebook 1.

Files and images stored in the database

PROBLEMINSTEADorders table20 MB PDF in a columnlogged, replicated, backed up, cachedrows3://...objectpath, size, checksumin the database
What you see
Backups, restores and replicas get slow and expensive. The cache fills with blobs.
Why it happens
Every byte is logged, replicated and backed up with the rest of the data, and it competes for the same memory.
Do this instead
Store files in object storage. Keep the path, size and checksum in the database.

Reports and exports on the primary

PROBLEMINSTEADprimarycheckoutbig reportscans push hot pages out of cacheprimaryreplicacheckoutreports here
What you see
Checkout or login slows down at the same time every day.
Why it happens
Big scans push hot pages out of the cache and use the CPU and I/O that short queries need.
Do this instead
Run them on a replica or a column store. Design doc.

A cache that is the only copy

PROBLEMINSTEADcachethe only copyrestart or failoverthe data is gonedatabasecachecache is a copyrebuilt from the database
What you see
Data disappears after a restart or failover.
Why it happens
Caches are built to lose data: eviction, restarts, failovers.
Do this instead
Keep the record in a database, and treat the cache as a copy that can be rebuilt.

An array that grows forever inside one MongoDB document

PROBLEMINSTEAD{ conversation: 42, messages: [ ...200,000... ] }creeping toward the 16 MB limit{conv: 42, msg: 1}{conv: 42, msg: 2}{conv: 42, msg: 3}one document per message
What you see
Updates get slower. Eventually a write fails at the 16 MB document limit.
Why it happens
Each change rewrites a bigger document, and BSON documents have a hard size limit.
Do this instead
One document per item (one per message, one per event), with an index on the parent ID. Design doc.

Entity-attribute-value tables

PROBLEMINSTEAD42 | color | black42 | ram_gb | 1642 | size | 15in42 | brand | acmeone row per attribute, joins to read one42 | laptop | 1299attrs: {...}one row, JSONB for the rest
What you see
Every product page is a dozen joins. No constraint can check a value.
Why it happens
Each attribute is a row, so reading one entity means reassembling it.
Do this instead
Common attributes as columns, the long tail in JSONB or a document. Design doc.

Money stored as a floating-point number

PROBLEMINSTEAD0.1 + 0.2= 0.30000000000000004floating point cannot store cents exactly10 + 20= 30 centsbigint cents, or numeric
What you see
Totals off by a cent. Reconciliation never quite matches.
Why it happens
Binary floating point cannot represent most decimal fractions exactly.
Do this instead
Integer cents (bigint), or numeric or decimal with a fixed scale.

Timestamps without a time zone

PROBLEMINSTEAD09:0009:00written in UTCread as Pacificsame value, 8 hours apart09:00+00timestamptz, or UTC alwaysone meaning everywhere
What you see
Events shift by hours after a server move or a daylight saving change.
Why it happens
A value without a zone means whatever the writer assumed.
Do this instead
In PostgreSQL use timestamptz. In MySQL, store UTC in DATETIME consistently. TIMESTAMP converts zones but ends in January 2038.

DELETE to enforce retention on a huge table

PROBLEMINSTEADDELETE ... WHERE created_at < ...millions of logged deletes, bloat, lagSepOctNovDecDROP PARTITIONone quick operation
What you see
Nightly deletes cause bloat, replica lag and I/O spikes.
Why it happens
Each deleted row is a logged change, and the space is reused only after cleanup.
Do this instead
Partition by time and drop or detach whole partitions. In MongoDB use a TTL index, and in Cassandra a TTL.

A new database connection per request, at scale

PROBLEMINSTEADdatabasea process and memory per connectionpooldbfew long-lived connections
What you see
Memory on the database grows with traffic. Connection storms after a deploy.
Why it happens
PostgreSQL starts a process per connection. Every engine spends time and memory on each one.
Do this instead
A connection pool in the application, and PgBouncer or ProxySQL in front when there are many application servers.
Your turn

A teammate wants to store each product's tag ids as a JSON array in the product row, to avoid a join table. When is that fine, and when does it hurt?

Write your answer down first. Then open mine.

Show my answer

Fine when: the tags are always read and written together with the product, nobody asks "which products have tag 42", and only one process edits them.

It hurts when: you need that reverse query. It needs a GIN index in PostgreSQL or a multi-valued index in MySQL 8.0, and it is still harder to get right than a join table. Nothing stops a deleted tag id from staying in the array. And two people adding a tag at the same time read the array, change it and write it back, so one change is lost.

What I would do: a join table, product_tags (product_id, tag_id) with a primary key on both. It is boring, and it answers every question.

Connected

Where this shows up

The same mechanism, caches and memory, concurrent writes and isolation, events across services, elsewhere on the site: in real incidents, in measurements, and in designs.

Part 3 of 4 · Design · 24 pagesAll pages

Which database does my application need? What kind of application data goes in which database, and why, as design docs, plus the anti-patterns and the decisions behind them.