Derived data: search, analytics and change capture
Search, analytics and per-customer history are copies of the truth. Build them from the commit log, promise how fresh they are, and make sure they can be rebuilt.
Derived data is any copy of the truth reshaped to answer a question the source answers badly. A search index, an analytics warehouse, a cache and the customer_orders table from the sharding chapter are all derived data. This chapter is about building such copies so that they agree with the source within a time we promise, and so that losing one is an inconvenience rather than an incident.
Two Dabba questions start it. At 20:10 a customer in Indiranagar types “paneer” into the search box and expects restaurants that are open now, deliver to her, have a matching dish in stock, and are ranked sensibly. Meanwhile the operations team wants average preparation time per restaurant per hour for the last 90 days, to find kitchens that slow down at the peak. Neither question should be asked of the order shards or the menu database.
Why the source database cannot answer the search box
By the brief, there are about 50,000 restaurants. With roughly 80 dishes each, the menu tables hold around 4 million dishes. The naive query is WHERE name ILIKE '%paneer%'. An ordinary B-tree index cannot help with a pattern that starts with a wildcard, because the index is sorted by the beginning of the string. So the database reads all 4 million rows, for every keystroke, for every customer, on the same menu database that is busy building menus for 16 million views a day.
Speed is only the first problem. Customers type “panner”, “panir” and “paneer tika”. They expect “cottage cheese” to find paneer and “biryani” to find “dum biriyani”. And the answer must be ranked by a mix of text relevance, distance, rating, delivery time and whether the restaurant is busy. A relational query can be bent into doing some of this, but the structure built for it is different.
That structure is the inverted index. Instead of storing, for each dish, the words it contains, it stores for each word the list of dishes that contain it. Building it starts with analysis: each dish name and description is lowercased, split into tokens, and normalised, so “Paneer Tikka (Half)” becomes the terms paneer, tikka, half. Synonym rules add cottage cheese as another way to reach paneer. Each term then points to a sorted posting list of dish ids.
A query runs the same analysis on what the customer typed, looks up each term’s posting list, and intersects or unions them. That gives candidate dishes in milliseconds no matter how many dishes exist. Filters (this city, open now, in stock, delivers to this location) narrow the candidates, and a ranking function scores what is left. BM25, the standard text-relevance score, gives more weight to rare terms and less to long descriptions that mention a word in passing. Dabba then blends in distance and rating.
Search is naturally local, so Dabba keeps one index per city. A Bengaluru query never needs Mumbai’s dishes, and a bad index rebuild in one city affects only that city.
Most “search is broken” tickets come from analysis that differs between indexing and querying. If the index stems “tikka” to “tikk” but the query analyser does not, a search for “tikka” finds nothing. Using the same analyser on both sides is a rule worth checking first.
Two ways to fill the copy
The index needs to change whenever a menu changes. The obvious approach is the dual write: the menu service updates the database and then sends the same change to the search engine. It reads well, and it drifts.
A restaurant owner taps “out of stock” on butter chicken at 20:01:00 and, realising she tapped the wrong dish, taps “in stock” again at 20:01:02. The two requests are handled by two different menu-service servers, each of which updates the database and then sends the change to the search index. What can the index end up showing, and for how long?
Show the worked answer
The database applies the two updates in the order they commit, so it ends correctly: in stock. The search index receives two separate HTTP calls from two servers. If the second server’s call is quicker (a garbage-collection pause on the first, a retry, a slow network path), the index applies “in stock” and then “out of stock”.
The index now says butter chicken is unavailable, and nothing will correct it until that dish changes again, which could be days. The restaurant loses orders for its most popular dish and the dashboards show nothing wrong. A related failure is simpler: the index call times out, the server logs a warning and moves on, and that one change is never applied.
Read the database’s own log instead
The fix is to stop asking application code to keep two systems in step. The database already records every committed change, in commit order, in its write-ahead log (Postgres) or binlog (MySQL), because that is how replicas stay in step. Change data capture, CDC, reads that log and turns each committed row change into an event with the row’s before and after values. Debezium is a widely used open-source connector that does this and appends the events to Kafka.
Because the events come from the commit log, they arrive in commit order, and if we key them by dish id, every change to one dish stays in one partition, in order. The butter chicken race cannot happen: the index sees “out of stock” and then “in stock”, the order the database committed them. A timed-out index write is not lost either: the indexer has not saved its offset, so it retries the same event.
Retries and replays mean the indexer sometimes applies an old change after a newer one, for example after it rewinds to rebuild. Versioned writes close that gap. Each event carries the log position at which it committed, and the indexer writes with that position as the document version. Elasticsearch’s external versioning rejects any write whose version is not higher than the stored one, so an old event arriving late is ignored instead of undoing a newer change.
CDC has costs worth naming. There is a connector to run, monitor and upgrade. The events mirror table structure, so renaming a column in the menu database becomes a breaking change for the indexer, the warehouse loader and anyone else reading the stream. Some teams prefer to publish deliberate domain events through the outbox from the previous chapter (“DishAvailabilityChanged”) so that consumers depend on a contract instead of a table layout. Dabba uses raw CDC for the search index and warehouse, which want every column anyway, and outbox events for things other teams build products on.
| How the copy is updated | Ordering | What goes wrong | What it costs |
|---|---|---|---|
| Dual write from application code | Whatever order the network delivers | Reordered and dropped updates, silent drift | Nothing up front; the bill comes later |
| CDC from the commit log | Commit order, per key | Consumers break when the table schema changes | A connector to operate; schema coupling |
| Outbox domain events | Commit order, per key | An event the author forgot to emit | Discipline in every write path |
| Periodic full rebuild | Not an issue; the copy is replaced | Stale between runs | Heavy reads on the source each run |
Freshness is a number we promise and measure
A derived copy is always behind the source. The question is how far, and whether that is acceptable for the thing it answers. Saying “eventually consistent” and stopping there leaves every team guessing. We write a freshness target for each copy and measure it.
For Dabba’s search index: availability changes are reflected within 30 seconds at p99; descriptions and photos within 10 minutes. The reason for the tight first number is money. A customer who orders a dish that went out of stock five minutes ago gets a cancellation and probably does not come back that evening. For the warehouse, 15 minutes is fine. For customer_orders, a few seconds.
The measurement is consumer lag expressed in time: the current time minus the commit timestamp of the last event the consumer applied. It is the same per-partition lag from the last chapter, with a target attached. When the lag on the Bengaluru search indexer passes 30 seconds, someone is paged, before customers start ordering dishes that do not exist.
One freshness problem is not about lag at all. The restaurant owner marks butter chicken out of stock, then opens her own menu page in the partner app to check. If that page reads from the search index, it may still show the dish in stock for a few seconds. She taps the toggle again, which turns it back on. The owner needs to read her own writes. So the partner app’s menu screen reads from the menu database, and only customers read from the index. Choosing which reader may see which copy is part of the design.
Analytics wants columns
The operations question was average preparation time per restaurant per hour for 90 days. That is about 90 million orders (1 million a day for 90 days). The query needs three fields from each: restaurant id, accepted time, and ready time.
A transactional database stores rows together on disk, because its usual job is to fetch or update one whole order. To read three fields it must read the pages holding entire rows. If an order row with its columns is around 1 KB, scanning 90 million of them reads about 90 GB, and it competes with dinner traffic for the same disks and memory. A column store keeps each column in its own files. The same query reads three columns of 8 bytes each, about 2.2 GB, and columns of similar values compress well, often by a factor of five or more. The difference between those two numbers is why Dabba runs analytics in a warehouse fed from the log, and why it never runs them on a production replica during dinner.
The warehouse is loaded in small batches every few minutes from the CDC topics. Because the log keeps seven days and the warehouse keeps raw events, we can change how preparation time is calculated next month and recompute history from the raw events. If the logic changes and history cannot be recomputed, last year’s numbers quietly disagree with this year’s.
Keeping the promise from the sharding chapter
The sharding chapter left a debt: orders are sharded by restaurant, and “my past orders” would be served from a customer_orders table sharded by customer id. That table is derived data, and building it shows the general recipe in a small space.
A consumer reads order-events. For each event it computes the customer’s shard and upserts one row keyed by order id: restaurant name, item summary, total, status and time. It does not append a row per event; it keeps one row per order and overwrites it as the order progresses, so the table holds the current picture of each order, which is all the history page shows.
Two details make it safe. Events for one order arrive in order, because the topic is keyed by order id, but the consumer may still see an event twice after a restart. So each row stores the sequence number of the last event applied, and the upsert only changes the row if the incoming event’s number is higher. A duplicate or a replayed old event becomes a no-op. And the restaurant name is copied into the row at the time of the order, rather than looked up when the page renders. If a restaurant later renames itself, past orders still show the name the customer ordered from, which is what a receipt should show, and the history page never needs to query another service.
Its freshness target is a few seconds. A customer who places an order and immediately opens her history might not see it yet, so the history page also reads her active orders directly from the order shards, which it can find from the order ids the app already holds, and merges them in. That is the read-your-writes problem again, solved by reading the source for the small part of the page where it matters.
Rebuild is the test
The property that makes a copy derived is that it can be rebuilt from the source. If we cannot do that, it is a second source of truth with no backups, whatever we call it.
Here is how that goes wrong in practice. A ranking engineer adds a “popularity” field that the search indexer computes by counting clicks on search results, storing the running total only in the index. Six months later a bad mapping change corrupts the Bengaluru index and it has to be rebuilt. The menus come back from the database. The popularity numbers do not, because the clicks were never kept anywhere else. Ranking for Bengaluru silently resets to six months ago. The fix is to make clicks an event stream of their own, retained in the warehouse, and compute popularity from that, so that it too can be rebuilt.
Rebuilding without downtime is routine once the pipeline is right. We create a new, empty index, start a consumer that snapshots the menu tables at a known log position, and then reads the stream from that position. When the new index has caught up, we switch the alias that queries use from the old index to the new one, and delete the old one later. If the rebuild produces something wrong, the alias still points at the old index and customers never notice.
Pipelines also need checking against the source, because bugs in consumers do not announce themselves. A nightly reconciliation job compares, per restaurant, the count of in-stock dishes in the database with the count in the index, and alerts on any difference. It is a dull job, and it catches problems that monitoring lag never would, since a consumer can be perfectly up to date and still wrong.
When a separate copy is not worth it
At ten cities, Postgres’s own full-text search, with a GIN index on a read replica, can answer “paneer” across 4 million dishes quickly enough. It supports stemming and ranking, and it needs no new system. A separate search engine adds a pipeline, a freshness target, a reconciliation job and an on-call rotation. Dabba should start there and move when the database version runs out: when ranking needs signals the database cannot combine efficiently, when typo tolerance and transliteration become product requirements, or when search load starts to hurt the replica’s other readers.
The same applies to every copy. Each one has a pipeline to run, a freshness target to measure and a rebuild to rehearse. A copy earns that cost when the source genuinely cannot answer its question; otherwise an index on the source is the cheaper answer.
Some questions do not need a full copy at all. “How many different customers looked at this restaurant this week?” and “which dishes are trending in Pune right now?” only need a small summary that is approximately right. The next chapter, on sketches, covers data structures that answer such questions in kilobytes, and how to tell when an approximate answer is acceptable.