Ch.66: Logging System Design: Finding One Error in a Billion

Outline

Transcript

0:00 Application logs record what services did: a request failed, a payment timed out, a connection closed. Centralized logging brings those records together so we can investigate across machines. You search for that checkout timeout, and routine request messages fill the results. The error you need is buried in there. Let's follow that error from collection to search, then decide what deserves an index. We'll narrow by service and time before reading messages. One error in a billion records doesn't require indexing every word.

0:30 With that narrower investigation in mind, here's the complete route. Checkout hands its record to a collector, a local agent that buffers and exports logs. Ingest is the backend's entry point: it checks the sender and accepts the batch only when replicated storage can preserve it. Index builders make stored records searchable. Search enters separately. The query service checks which customer company, or tenant, the caller may access. The requested service and interval select what we open. Storage keeps the original timeout record, not just an error count.

1:02 We'll return to this same map with our timeout record. First, let's decide what a useful answer actually includes. Before filling in those components, our functional requirements start with one investigation. For the caller's company, find checkout-service errors from the last 15 minutes whose message contains the literal text, payment timeout. Return the original matching records. And keep that text test precise. For this exercise it's a case-sensitive substring match. We aren't silently changing it into, find anything vaguely about payments.

1:33 Right. We also need access isolation, a way to retry exports without inventing extra events, and retention. Assume 7 days of interactive search and 30 days of compressed raw records. Those retention and access promises also need resource limits. Our non-functional requirements keep the application responsive: logging can't wait indefinitely on a slow receiver. Collector memory, record size, query work and each tenant's resource use all need bounds. For selected interactive queries, let's aim for a 2-second response and 30 seconds of normal ingest-to-search delay.

2:06 Those are load-test targets, not guarantees we get by drawing arrows. Yes. Diagnostic logs explain a payment; the business ledger records whether it committed. A missing log is a missing clue, not permission to erase a sale. Business events that must never disappear need their own durable transaction path. How much data sits behind that response-time target? Let's size a concrete case before choosing the search workers. Assume 100,000 records a second, averaging 500 bytes before compression. That's 50 megabytes a second, which adds up to 4.32 terabytes a day in decimal units.

2:43 30 days is almost 130 terabytes before indexes and extra copies. My first thought was to store the files cheaply and search them when somebody asks. A narrow scan can be perfectly reasonable. Suppose 1,000 services contribute equally. One service's 15-minute window has 90,000 records, about 45 megabytes of original data. That seems manageable. But checkout might be much busier than the average service. What happens if it produces 10% of all the logs? The same window now contains nine million records, or 4.5 gigabytes.

3:16 Nothing about the query's wording changed; it selected a hundred times more data. Ah, the service filter looked reassuring until we put traffic behind it. We still have the same response deadline for far more work. Processing that whole window in 2 seconds would require 2.25 gigabytes of original records per second, with no time left for the other query work. That's a rate requirement, not a benchmark from a system we haven't built. So cheap storage hasn't answered whether our investigator gets a timely result.

3:49 Right. Compression and parallel reads help, but neither this arithmetic nor the word distributed proves the target. Measure the hot query, not just a company-wide average. And before choosing those reads, we need records whose fields mean the same thing across all those services. That traffic comparison leaves another question: what do we need inside each record to make the query interpretable? For this record, service is checkout, severity is error, and the message body is payment timeout. The application reports when the timeout happened; a separate observed timestamp tells us when our collection path saw it.

4:24 OpenTelemetry makes that distinction in its log model; source links are in the description. Think of a letter's date and its arrival stamp. A delayed export carries an old event time into a newly observed batch. Treating those clocks as interchangeable would hide the delay. The tenant field needs a different source of truth. We derive it from the authenticated exporter, rather than trusting a company name inside the submitted record. Sure. For example, a tenant can't write another tenant's ID into its payload and acquire that tenant's storage or query access.

4:57 Authorization fixes the boundary before we organize the data. Now imagine the exporter loses a response and sends the same batch again. Could we remove duplicates by comparing message text? Two real payment attempts could produce identical messages. Give each event a stable identity: its producer, that process run, and a sequence number. Call our timeout event 7 in this checkout process run. Every retry keeps that same identity; restarting the producer starts a different run. So matching text can still mean separate events.

5:30 A repeated identity means another delivery of an event we already have. Exactly. We keep a bounded history of those identities covering our supported retry window. Beyond that window, the exporter can't assume the same guarantee. Once records have stable identities, how do we export them without making checkout wait for the receiver? Put a bounded queue between application logging and network export, so a brief slow receiver doesn't immediately stall a customer request. Remove known forbidden fields before queuing records or saving them on disk.

6:02 Those local copies count too. Once the last queue slot fills, the next record can't make the queue bigger. Policy must drop it or move pending records into bounded local files, a disk buffer for a longer interruption. I think I'd initially ask for disk everywhere. Dropping the exact error we're trying to investigate feels awful. Disk helps, but it isn't unlimited, and it can share a failure with the application host. We still need a maximum footprint and a policy for a full or failed disk. Yeah, otherwise the logging outage becomes a checkout outage.

6:36 A diagnostic feature has promoted itself to a dependency. Yeah, and now the checkout failure can hide the logging failure too. A loss counter can't rely only on that saturated queue. Export a bounded health signal through a separately monitored path, so dropping logs doesn't erase the evidence of dropping them. For instance, disconnect a collector and keep sending requests. The test should show a bounded footprint, customer work continuing, and an observable loss or disk-buffer condition. Not a process slowly consuming the machine.

7:08 That local queue still leaves the host-loss boundary open. When does the backend take stronger responsibility for the records? At ingest, our exercise promises that an accepted batch survives one failed host. One receiver putting the batch in memory obviously isn't enough. Would writing it to that receiver's disk settle it? Not for losing that host. Ingest sends event 7's batch to replicated append storage: it adds batches to stored history across hosts. Its protocol persists this batch on two of three distinct hosts before acknowledging acceptance, and its recovery rules preserve those acknowledged records after one host fails.

7:46 Okay. We're buying a defined recovery guarantee, not assuming two completed writes alone establish it. The protocol and its failure assumptions are part of the dependency. At that incoming rate, are we starting a three-machine exchange for every record? No. That storage protocol coordinates a batch at a time, so records share the fixed work. We still have to measure how long batches wait against our freshness target; the disk writes don't become free. Yes. Ingest authenticates the exporter, validates record sizes and fields, then submits the batch. If the append service can't meet that durability condition, it doesn't issue a successful acceptance response.

8:22 For example, event 7 is accepted, but the response gets lost. The collector sends it again. The append component must recognize that durably recorded identity and confirm acceptance without creating another logical event. That identity history belongs to the durable append guarantee too, within its promised retry period. Recover the accepted identities with the records. An empty in-memory table after a restart would mistake our second delivery for a new event. And acceptance doesn't say the record is searchable yet.

8:54 Index builders are downstream; let's look at the work we're asking them to perform. Next, those builders could create a full-text index, turning message words into lists of record IDs. In a separate four-record example on screen, record 1 says payment timeout, 2 says payment declined, 3 says inventory timeout, and 4 says timeout while waiting for payment. Walk me through the search mechanism. How do those lists find a timeout without reading every stored message? First, text analysis breaks messages into searchable tokens.

9:25 The index lists records 1, 2 and 4 under payment, and records 1, 3 and 4 under timeout. Intersect those lists and you get 1 and 4. Let me compare the two matches. One has payment immediately followed by timeout. In 4, timeout comes first and payment is at the end. Only the first contains our literal text. Right. Different matching rules: token search checks analyzed words; phrase search also checks order and adjacency; substring search checks the original character sequence, even inside a word. Word cards aren't the same as laying an exact strip of letters over the message.

10:02 Agreed. Returning the wrong interpretation quickly hasn't rescued the investigation. No. A fuller engine can store positions and perform more checks, but it still has to implement our promised test. Every indexed token adds write work, storage and maintenance. Elastic documents the token-to-document approach; it doesn't make that bill disappear. Then a text engine earns that bill when people need varied content searches. Our investigation already names a company, a service and a short interval. Could those fields narrow the data before we examine words?

10:35 That narrower query creates an alternative to indexing message content. Let's unpack it: what would the index point to instead? Loki, a log backend, illustrates this choice. A stream groups records with the same label values. Its index locates those groups; compressed blocks called chunks hold their records. The query selects streams and time ranges, then scans the relevant chunk contents. Like an archive organized by company, service and date: the catalog gets you to a small set of folders, but it doesn't list every word on every page.

11:09 Yeah. The word lookup names pages containing timeout; the folder catalog only narrows the material worth opening. The difference is how much message content the index knows about. The 45-megabyte window makes that catalog-plus-reading approach plausible. Our 4.5-gigabyte hot window makes its limit visible. Indexing less hasn't abolished the work; some of it moves to the query. An engineer often knows which order failed. Couldn't we make the catalog more selective by adding order IDs as labels? Grafana engineer Ed Welch walks through that choice in his 2023 label guide.

11:44 Adding an order ID splits records into many small streams, with more index entries and small chunks to manage. Ah, I was counting the easier lookup and not the fragmentation. Every useful search field doesn't have to become another grouping boundary. Exactly. Cardinality means the number of distinct values or combinations. Keep stream labels low-cardinality; put highly variable details in the records or in a separately designed index. Welch's example explains the mechanism, not a universal performance ratio.

12:15 Sure. Our fictional service can choose its own layout. We aren't claiming this map is Loki's entire implementation. Now follow our checkout query. First, authorization selects the company. Next, service metadata and the requested interval identify candidate chunks, and severity filtering discards records we don't need. We decompress selected data and apply the declared message substring test. Our payment timeout comes back with service checkout, severity error and event 7's identity. Merge matches in a defined order and keep each identity, so a retried batch doesn't inflate the result.

12:47 I think that metadata-selected scan is a sensible starting point for this query mix. Then measure bytes read, decompression work and response time for both average and hot services. Here's the objection I'd expect from an on-call engineer: I don't always know the service. Sometimes all I have is part of a message. Do we tell them to guess better? No. That need changes the design. Offer a broader, explicitly slower search class, and measure how often people need it. If varied message search is routine, fuller text indexing may be worth its ingestion and storage cost.

13:24 Or, for example, if investigators repeatedly search a normalized payment error code, we could index that field rather than every arbitrary word. Yes, provided the code has a defined meaning and we measure its index cost too. That's a targeted addition, not permission to turn every payload value into a stream label. I like that the choice can change without pretending the first version was foolish. A search index is useful when it saves work the investigation actually does. Exactly. Keep the same records and promised matching rule when comparing designs; a faster answer that misses valid records hasn't won.

14:00 Bound concurrent reads and scanned bytes per tenant. Stop or move a too-broad query into the slower class instead of exhausting everybody's workers. But limiting search work also limits what an empty screen can tell us. Suppose a relevant storage partition failed while searching and no checkout errors appear. Have I actually ruled out an outage? Show the failure and partial coverage. An empty result then means no matches in the searched view, not proof that no error happened anywhere. Freshness needs similar care.

14:30 Our 30-second normal target isn't a claim that every just-accepted event is already indexed. Elasticsearch's refresh mechanism is one real example of search visibility following ingestion. For this design, each partition reports a checkpoint: how far through its accepted records the builders have made data searchable. Our timeout might be accepted but beyond that checkpoint. Return those positions and failed reads with the answer, rather than inventing one global instant. Okay, suppose page 1 finds event 7.

15:00 While I read it, a delayed batch adds an older checkout error. I click next. Does the new error get inserted ahead of where I stopped? The delayed error stays out of page 2 of that saved search. We continue through the records available when we opened page 1, not whatever happens to be searchable later. So next has to refer to that original group of records, not just the last line I read. Right. Retain the exact chunk versions used by this search, plus a bounded copy of records that are searchable but still in memory.

15:33 The token binds that edition, tenant, filters and position, and expires. If those saved contents are unavailable, report expiry instead of substituting new data. So a fresh query can find the late error without changing my older paginated result. We haven't promised a permanent snapshot or a total event-time order across machines. Precisely. Event time still helps investigate the incident, but clock differences and delayed arrivals don't vanish because we've sorted the display. That temporary read view leads to retention: stored data also expires.

16:07 Our 7-day interactive tier and 30-day raw archive serve different costs and query speeds. Keep recent indexes and query capacity near the active investigation. Older compressed records can remain in object storage, with a separate job that scans the selected archive range. For example, yesterday's checkout query can be interactive; the same investigation 3 weeks later might submit an archive job. Keeping the bytes doesn't preserve the original response-time promise. Yes, and retention must remove index references along with their records.

16:38 Otherwise search advertises results whose content has already expired, or leaves a path to data that was meant to disappear. Privacy belongs earlier than expiry, though. If checkout accidentally includes a known forbidden field, hiding it in the result page is too late; it's already in the stored chunks and their copies. Agreed. That's why collection strips known disallowed fields before saving local files, and ingest enforces the same policy before durable storage. Test downstream stores too. We aren't promising to recognize every possible secret embedded in arbitrary text.

17:12 I'd put a fake secret value in the test data and search the persisted outputs for it. The policy needs evidence where the bytes are saved, not just where a person sees them. That fake-secret test opens the broader reliability run. Go back to event 7: acceptance succeeded, but the collector didn't hear the response. What should its retry leave us with? One event with that identity. But suppose the implementation simply discards every repeated message. That retry test might pass while we lose two genuine payment failures.

17:45 Then send two events with different identities but the same timeout message. Both must remain. After that, lose one accepted replica and recover through the declared append protocol. Check that event 7 still exists, not just that a replacement worker turns green. Now pause the receiver and fill the collector. Checkout must continue while memory or local files stay bounded and the loss condition stays observable. And the backend eventually returning doesn't prove that happened. Run a hot tenant's broad search beside another tenant's small lookup. The broad query's work budget must stop it consuming all the shared search capacity.

18:23 Finally, delay an export and fail a relevant query partition. The results should expose freshness and missing coverage, while a continuation preserves its original read view or reports that the view expired. So each test checks a different promise. One successful retry doesn't prove loss handling, privacy and fast search all at once. Yeah. Then load-test the query mix with the actual compression, indexes and hot-service distribution. If the 2-second goal misses, our measurements tell us whether to add indexing, read capacity or a different query class.

18:55 Now those failure tests bring us back to the complete map. How does our checkout error travel through the system we chose? Checkout emits the timeout with a stable event identity. The collector applies redaction and exports within its limits. Authenticated ingest validates that policy, and replicated storage takes responsibility before success. Right, our accepted timeout is now safe under that host-failure promise. Builders still have to make it searchable. The investigator's company, checkout service and selected interval narrow the chunks, then the message test finds our timeout.

19:28 The answer carries its read coverage, not just a reassuring empty box. The index choice follows that investigation. Broader message searches can justify more indexing, but they don't require us to pay for every possible search on every write. So I'd begin with an explicit query promise and an honest cost measurement rather than a giant index built for questions nobody asks. We can add capability when the investigation proves it needs one. And I'd keep checkout responsive before optimizing the convenience of the logging backend. Losing diagnostic evidence is painful; letting its collection take down checkout is worse.

20:04 A useful log system keeps the records, finds the relevant ones and tells you what it couldn't inspect. Thanks for listening to Learning Podcasts.