Why do big apps read from copies of their database?
Post a comment, refresh, and it may be gone for a second: your refresh asked a copy that has not heard the news yet.
▶ Start the storyBig apps read from copies of their database because one machine can only answer so many questions at once. The trick is to split the work. One primary database takes every write, such as a new post or a changed password, and logs it. Copies of that database, called , receive the logged changes and mostly serve read requests. When the load is read-heavy, you can add replicas instead of buying an ever bigger machine, and so scale out beyond the capacity of a single database instance.
A read replica is a read-only copy of the primary. It can be looked at but never changed. Routing queries to reduces the load on the primary, and it also protects it: business reporting and queries can run against a replica rather than the production instance, so a heavy report does not slow down the shop.
Primary
- Takes all writes
- Logs the changes
- Always up to date
Read replica
- Read-only copy
- Receives changes
- May serve stale data
There is a catch, and it can make a comment you just posted seem to vanish when you refresh. are usually updated , so a change reaches them a little after it is committed. They may serve stale data because of , the delay in propagating changes from the leader. In PostgreSQL the delay is typically under one second if the replica can keep up, but running the same query on primary and replica at nearly the same moment can return different results.
Copies also help when things break. A read replica can be to a standalone database as a disaster recovery solution if the primary fails. But the lag matters again: if the primary crashes, some committed transactions may not have reached the replica yet, and the data loss is proportional to the replication delay at that moment.
Quiz me
0/3
Recap
One primary takes the writes and replicas serve the reads, trading a little staleness for much more capacity.
💡 A trick to remember it · The primary writes the book; replicas read from photocopies, a little behind the original.
Surprising fact · Because copies update asynchronously, the same query run on the primary and a replica a moment apart can return different answers.
Sources (4)
No source, no claim. Every fact in this lesson (12 claims) cites at least one of these.