Courses / System Design Interview / Chapter 21
Module 4 · Building Blocks III: Limits, Storage and Search · Chapter 21 of 49
Distributed Logging
Builds on Core Concepts: RPCs, Consistency, Failures and Time, Building Blocks: The Parts Every Design Reuses, Distributed Monitoring: Metrics, Logs and Traces, Monitoring Client-Side Errors, Distributed Message Queues and Distributed Search. Next up: Distributed Task Schedulers.
Part 1 · Why central logs, and logs versus metrics
Logs on forty machines
When a customer says an order failed at 9:42, someone has to find the line that explains it. If the service runs on forty servers, that line is on one of forty disks, or on a container that was replaced an hour ago and took its disk with it.
Central logging means every server sends its logs to one place, where they are kept, indexed and searched together. Three problems push every large system there. The logs of a machine that crashes or is replaced are lost with it. Searching forty machines by hand is slow and error-prone. And one user request passes through several services, so its story is split across several machines and only makes sense when put together.
OpenTelemetry describes a log as a timestamped record, structured or unstructured, with optional metadata. A good log line answers when, where, who and what. The OWASP logging cheat sheet lists the same four: when the event happened, where in the system it happened (service, version, host, code location), who was involved (the user or the source address) and what it was (an event type, a severity and a description).
What logs add to metrics
The monitoring chapter showed metrics, which are cheap numbers per time bucket, and logs, which are one record per event. They are partners. Metrics are good for noticing that something is wrong and for alerts. Logs are good for finding out exactly what went wrong for one request.
| Metrics | Logs | |
|---|---|---|
| Shape | A number per series per time step | One record per event, with fields or free text |
| Size grows with | Number of series, not traffic | Traffic: one line or more per request |
| Good for | Alerts, trends, dashboards | Debugging one case, audits, security events |
| Cost to keep a year | Low | High, and it rises with traffic |
| Question | How many failed? | Which ones failed, and what did they do? |
The fourth row is why this chapter spends time on cost. A metric series costs the same whether a service handles ten requests a second or ten thousand. A log costs more as traffic rises. Teams that log everything at full detail for a year learn this from the bill.
The pieces of this chapter follow one line's life. It is written in a structured form with an id, shipped from the machine, stored and indexed, kept for a while in cheaper and cheaper places, and, on the way, filtered for noise and for secrets.
Severity and the log record
Every log line has a severity, which says how serious it is. Syslog, the long-standing logging protocol described in RFC 5424, defines eight levels numbered from 0 for Emergency to 7 for Debug, with Error at 3, Warning at 4 and Informational at 6. Lower numbers are more severe. OpenTelemetry uses a different scale: severity numbers from 1 to 24, grouped into six bands, TRACE (1 to 4), DEBUG (5 to 8), INFO (9 to 12), WARN (13 to 16), ERROR (17 to 20) and FATAL (21 to 24), where larger numbers are more severe. Most application code uses the familiar names DEBUG, INFO, WARNING and ERROR and lets the pipeline convert.
The OpenTelemetry log record has a standard set of fields. The ones that matter most are the timestamp, a trace id and span id that link the line to a trace, the severity, the body (the main content, text or structured) and attributes, extra key-value details. The trace id is what lets you jump from a slow trace to the log lines it produced. The next lesson builds the same link from a simpler request id.
Why do logs need to be sent off the machine that wrote them?
- A crashed or replaced machine takes its disk with it, and searching many machines by hand is slow.
Which grows with traffic: the cost of a metric series or the cost of logs?
- Logs. A metric series costs about the same at any traffic. Each request adds log lines.
In syslog, which is more severe: severity 3 or severity 6?
- 3 (Error). Syslog numbers run from 0, the most severe, to 7, the least.
Part 2 · Structured logs and correlation ids
Text for people, fields for programs
An unstructured log line is a sentence: payment of 499 failed for user asha after 2 retries. A person can read it. A program has to guess where the amount ends and the name begins, and every service words its sentences differently. A structured log writes the same facts as named fields, usually one JSON object per line, so that a program can filter on status and group by service without guessing.
Structured lines also avoid a security problem. If a line is built by pasting user input into text, a user can include a newline and a fake line that looks real. The OWASP cheat sheet calls this log injection and recommends structured formats and cleaning newlines out of user input. A JSON encoder escapes the newline for you, as the fifth lesson shows.
Choose field names once and keep them across services: service, request_id, level, msg, and fields for the facts of the event. The names become the vocabulary of every search and alert, and renaming them later is expensive.
The correlation id
One user action often causes calls through several services, each writing its own lines. A correlation id, also called a request id, ties those lines together. The first service to see the request creates it, and every call it makes passes it on, usually as an HTTP header such as X-Request-ID. Each service puts it on every line it writes while handling the request. Then one search on the id returns every line of the request, from all machines. Sort them with care: clocks on different hosts drift apart, as the core concepts chapter explained, so two lines a few milliseconds apart on two hosts can sort the wrong way round. Within one service, the order in which lines were written is reliable.
In a program, the id has to reach every log call without passing it through every function by hand. Python has contextvars, which hold a value for the current request even when handlers run in different threads, and a logging formatter can read it when it builds each line. Other languages have the same idea under other names, such as thread-local storage or a context object.
The trace id from the monitoring chapter is a correlation id with a standard format. If your system has tracing, use the trace id and the same search then jumps between traces and logs. If it has none, a request id is a good start.
Two services and one id
The program starts two small services in one process, a gateway on port 55468 and an orders service on port 55469. The gateway creates the id, logs, calls orders with the id in a header, and logs the reply. Both write JSON through a shared formatter that reads the id from a context variable. The first block sets up the formatter and a helper to start a service. The second block defines the two services and sends two requests.
import contextvars import json import logging import sys import threading import uuid from http.server import BaseHTTPRequestHandler, HTTPServer request_id = contextvars.ContextVar("request_id", default="-") class JsonFormatter(logging.Formatter): def format(self, record): return json.dumps({"service": record.name, "request_id": request_id.get(), "msg": record.getMessage()}, separators=(",", ":")) handler = logging.StreamHandler(sys.stdout) handler.setFormatter(JsonFormatter()) logging.basicConfig(handlers=[handler], level=logging.INFO)
structured.py, part 1: a JSON formatter that adds the request id
def service(name, port, work): log = logging.getLogger(name) class H(BaseHTTPRequestHandler): def log_message(self, *args): pass def do_GET(self): rid = (self.headers.get("X-Request-ID") or uuid.uuid4().hex[:8]) request_id.set(rid) log.info("received %s", self.path) work(self, log, rid) self.send_response(200) self.send_header("Content-Length", "0") self.end_headers() srv = HTTPServer(("127.0.0.1", port), H) threading.Thread(target=srv.serve_forever, daemon=True).start() return srv
structured.py, part 2: a service that reads or creates the request id
import urllib.request from structured import service def orders_work(handler, log, rid): log.info("loaded order 17") def gateway_work(handler, log, rid): req = urllib.request.Request("http://127.0.0.1:55469/orders/17", headers={"X-Request-ID": rid}) status = urllib.request.urlopen(req).status log.info("orders replied %s", status) orders = service("orders", 55469, orders_work) gateway = service("gateway", 55468, gateway_work) for _ in range(2): urllib.request.urlopen("http://127.0.0.1:55468/checkout") orders.shutdown() gateway.shutdown()
structured_run.py: gateway calls orders, twice
{"service":"gateway","request_id":"a7406194","msg":"received /checkout"}
{"service":"orders","request_id":"a7406194","msg":"received /orders/17"}
{"service":"orders","request_id":"a7406194","msg":"loaded order 17"}
{"service":"gateway","request_id":"a7406194","msg":"orders replied 200"}
{"service":"gateway","request_id":"99b99762","msg":"received /checkout"}
{"service":"orders","request_id":"99b99762","msg":"received /orders/17"}
{"service":"orders","request_id":"99b99762","msg":"loaded order 17"}
{"service":"gateway","request_id":"99b99762","msg":"orders replied 200"}Python 3.12.10. The request ids are random and differ on every run.
Part 3 · Collection pipelines
From the app to the store
Applications should not talk to the log store directly. If the store is slow, the application slows with it, and a store outage would become an application outage. Instead the application writes its lines locally, to standard output or a file, and a separate program does the shipping.
That program is a log agent, one on every host. It tails the log, adds details such as the host name and the service version, groups lines into batches and sends them. It sits on the machine so that the application does not need to know anything about the destination. Changing where logs go means changing agent configuration, not application code.
Batching is the main efficiency. Sending each line as its own request costs a network round trip and a store write per line. Sending 100 lines per request cuts the number of requests a hundredfold. The price is delay: a line waits until its batch is full or a timer fires, so agents send on size or on time, whichever comes first.
A queue in front of the store
A burst of traffic or an incident multiplies log volume exactly when you most need the logs. If a hundred agents send straight to the store and the store cannot keep up, lines are lost, or the agents' memory fills up. A common remedy is a message queue between the agents and the store, as the message queue chapter describes. The agents write to the queue, which is built to absorb bursts, and the store reads from it at its own pace. The queue's depth is a saturation signal for the logging pipeline itself.
A pipeline still needs a decision for when everything is full. The agent has a bounded buffer, and when it is full there are two choices. Block the application until space frees up, which protects the logs and hurts users. Or drop lines and count them, which protects users and loses data. Almost every system drops, and the count of dropped lines becomes a metric. A silent drop is the failure to avoid: if the numbers are wrong, someone has to be able to find out.
| Stage | Job | What happens when it is slow |
|---|---|---|
| Application | Write lines to stdout or a file | Must never wait for the pipeline |
| Agent | Tail, batch, add host details, send | Buffer fills; drops and counts |
| Queue | Absorb bursts, decouple | Depth grows; retention limits apply |
| Store | Index and keep lines | Falls behind; the queue holds the rest |
A buffer under a burst
The simulation below uses logical time instead of a real clock, so its output is exact. Each tick, some lines arrive at an agent. The agent buffer holds at most 300 lines. Each tick the store accepts two batches of 100 lines. Traffic is 60 lines per tick, then three ticks of 250 lines, then back to 60.
from collections import deque CAPACITY = 300 # lines the agent may hold in memory BATCH = 100 # lines per request to the store STORE_RATE = 2 # batches the store accepts per tick buffer, shipped, dropped = deque(), 0, 0 arrivals = [60, 60, 250, 250, 250, 60, 60, 60, 60, 60] # lines per tick print("tick arrived buffer shipped dropped") for tick, n in enumerate(arrivals): for _ in range(n): if len(buffer) < CAPACITY: buffer.append("line") else: dropped += 1 # count it, never block the app for _ in range(STORE_RATE): for _ in range(min(BATCH, len(buffer))): buffer.popleft() shipped += 1 print(f"{tick:>4} {n:>8} {len(buffer):>7} " f"{shipped:>8} {dropped:>8}") print("arrived", sum(arrivals), "shipped", shipped, "dropped", dropped, "in buffer", len(buffer))
shipper.py: a bounded buffer, batches and a drop counter
tick arrived buffer shipped dropped 0 60 0 60 0 1 60 0 120 0 2 250 50 320 0 3 250 100 520 0 4 250 100 720 50 5 60 0 880 50 6 60 0 940 50 7 60 0 1000 50 8 60 0 1060 50 9 60 0 1120 50 arrived 1170 shipped 1120 dropped 50 in buffer 0
Python 3.12.10. A logical-time simulation, so the output is deterministic.
For the first two ticks the store keeps up and the buffer is empty. In the burst, 250 arrive but the store takes only 200, so the buffer grows to 50, then 100. In the third burst tick it would need 350 lines, but the cap is 300, so 50 lines are dropped and counted. After the burst the store catches up, the buffer empties and nothing else is lost. Of 1,170 lines, 1,120 were shipped and 50 dropped. A larger buffer, or a queue in front, would have saved those 50. The counter is why you know it happened.
The path as a scene
The scene follows one line of a request through the whole pipeline: servers write, agents batch, the queue absorbs, the store indexes, and a search finds all lines by request id.
Watch for the request id: servers 1 and 2 log lines with the same id
Read it as steps
Servers write lines, agents batch them, a queue absorbs bursts, and the store lets you search by request id.
Each hop is a place where a line can be delayed or lost, and each has its own measure: agent drops, queue depth, store lag. Watching the pipeline is the same discipline as watching any other service. Treat the logging system as a service with its own targets.
Why should the application not send logs straight to the store?
- A slow or failed store would then slow or fail the application. Writing locally and shipping separately keeps the two apart.
In the run, 50 lines were dropped. What would have prevented it, and what tells you it happened?
Part 4 · Indexing, retention and cost tiers
Finding a line fast
A search over a day's logs for one request id must not read a day of logs. A log store builds an index, a structure mapping values to the lines that hold them, so a lookup touches only the matching lines. The inverted index from the search chapter is the usual choice: each term points to a list of lines. Some stores index every word of every line. Others index only chosen fields, such as service, level and request id, and scan the rest when asked. Fewer indexed fields means a cheaper store and a slower search for the rest.
An index costs space and write time, often a sizeable fraction of the size of the data itself. That is a good deal for the last few days, when you search often, and a bad one for last year's logs, which you almost never touch.
So stores keep logs in tiers. A hot tier holds the latest days on fast disks with a full index. A warm tier holds older data, compressed and lightly indexed. A cold tier keeps the oldest data compressed in cheap object storage, searched slowly or loaded back when needed. Data moves down by age.
Retention and what it costs
Retention is how long a tier keeps data before deleting or moving it. The right numbers come from need, not habit. Debugging often needs only a week or two of detail. Audit and security rules may need a year or more of selected events. Many teams keep everything for a short time and keep only the important lines, such as errors and audit events, for a long time.
Compression changes the cost. Logs are repetitive: field names repeat in every line, and so do routes and service names. Standard compressors such as zlib or zstd shrink them a great deal. How much depends on the data, so measure on your own lines and not on a figure from a blog.
The next program builds 20,000 synthetic JSON lines, compresses them with zlib and then estimates the daily volume and the size of each tier under stated assumptions: 2,000 lines per second, a hot tier that is 1.5 times the raw size because of the index (an assumption, not a measurement), and the measured compression ratio for the others.
import json import random import zlib random.seed(9) ROUTES = ["/orders", "/cart", "/search", "/pay", "/login"] lines = [] for i in range(20000): lines.append(json.dumps({ "ts": 1790000000 + i // 40, "service": "web", "request_id": f"{random.getrandbits(32):08x}", "route": random.choice(ROUTES), "status": random.choice([200] * 95 + [404, 500]), "ms": random.randint(5, 400)}, separators=(",", ":"))) raw = "\n".join(lines).encode() packed = zlib.compress(raw, 6) ratio = len(raw) / len(packed) print(f"{len(lines)} lines, {len(raw) / len(lines):.0f} bytes each") print(f"zlib level 6: {len(packed) / len(lines):.0f} bytes each, " f"{ratio:.1f}x smaller") per_sec = 2000 # assumed: lines per second, total day = per_sec * 86400 * len(raw) / len(lines) / 1e9 print(f"\nraw per day: {day:.1f} GB") for tier, days, size in [("hot, searchable", 7, day * 1.5), ("warm, compressed", 30, day / ratio), ("cold, compressed", 365, day / ratio)]: print(f"{tier:<17} {days:>3} days x {size:5.1f} GB = " f"{days * size:7.0f} GB")
storage.py: measure compression, then estimate size per tier
20000 lines, 97 bytes each zlib level 6: 11 bytes each, 8.7x smaller raw per day: 16.7 GB hot, searchable 7 days x 25.0 GB = 175 GB warm, compressed 30 days x 1.9 GB = 58 GB cold, compressed 365 days x 1.9 GB = 701 GB
Python 3.12.10. The seed is fixed. The sizes follow from the assumptions in the code.
Choosing what to keep
Three levers cut the bill without losing what you need. Reduce volume at the source by not writing lines nobody reads. Reduce what is indexed by indexing only the fields you search. Shorten the hot tier by moving data to cheaper tiers sooner. A fourth lever, sampling, is in the next lesson.
| Lever | Saves | Cost |
|---|---|---|
| Write fewer lines | Network, agents, queue, store | Less detail when debugging |
| Index fewer fields | Store space and write time | Slow scans for unindexed fields |
| Shorter hot tier | The most expensive disks | Older searches are slower |
| Compress older data | Space, by a large factor | processing time and slower reads |
Why not keep a full index on all logs for a year?
- An index can be as large as the data, and old logs are rarely searched. Tiers give fast search for recent data and cheap storage for old.
In the run, the synthetic lines shrank 8.7 times. Why might your own logs shrink less?
- These lines are short, regular and repeat their field names. Real lines have longer free text, which compresses less.
What decides how long each tier keeps data?
- How long the data is useful for each purpose, such as debugging or audit, and what each tier costs.
Part 5 · Levels, sampling and keeping secrets out
Levels are a contract
A level tells the reader, and the pipeline, how to treat a line. Teams do best with a short written meaning for each. A common one: ERROR means a request failed or something needs a person; WARNING means something unexpected that was handled; INFO is a normal event worth a record, such as an order created; DEBUG is detail for developers and normally off in production.
Two habits keep levels useful. Production runs at INFO, with DEBUG switchable per service for a while, because DEBUG can be many times the volume of everything else. And ERROR must mean something, as with paging: a service that logs an ERROR for every user typing a wrong password teaches everyone to ignore ERROR.
The store can use levels to decide retention: keep all ERROR and WARNING lines for months, keep INFO for days, and keep DEBUG only where it was switched on.
Sampling, without breaking stories
When volume is too high even after sensible levels, sampling keeps a fraction of the lines. The client errors chapter sampled per session from a hash of the id, and the same rule applies here. Dropping each INFO line with probability 90% keeps scattered lines of each request, and the story of any one request is gone. Sampling per request, from a hash of the request id, keeps every line of a request or none of them.
Never sample away warnings and errors, since they are the lines you need most. Because the decision comes from the id, every service makes the same choice without talking to the others.
import hashlib import random random.seed(4) RATE = 0.10 # keep 10% of INFO requests def keep(request_id, level): if level in ("WARNING", "ERROR"): return True # never drop the bad ones h = int(hashlib.sha1(request_id.encode()).hexdigest(), 16) return (h % 1000) / 1000 < RATE # same id, same answer total = kept = 0 for i in range(10000): rid = f"{random.getrandbits(32):08x}" level = "ERROR" if i % 50 == 0 else "INFO" for _ in range(6): # six lines per request total += 1 kept += keep(rid, level) print("lines written:", total, " kept:", kept, f" ({100 * kept / total:.1f}%)") # Every line of one request lands on the same side of the decision: print({keep("0badc0de", "INFO") for _ in range(6)})
sampling.py: keep every WARNING and ERROR, and 10% of INFO requests
lines written: 60000 kept: 7302 (12.2%) {False}
Python 3.12.10. The seed is fixed, so the numbers repeat.
The program writes six lines for each of 10,000 requests, and one request in 50 is an error. It kept 7,302 of 60,000 lines, 12.2%, a little over 10% because every line of an error request is kept. The last line calls the decision six times for the same id, and gets the same answer each time: all six lines in or all six out.
Keeping secrets out
Logs are copied to many places, searched by many people and kept for long. Anything sensitive written to one is likely to leak. As the client errors chapter noted, the OWASP cheat sheet says these should not be logged directly, and if they must be, they are removed, masked, hashed or encrypted: tokens, passwords, keys and card data.
The best protection is to not pass such values to the logger at all. A second layer is a filter that runs on every record before it is written and masks anything that looks like a secret. The program below installs one: it redacts token=, password= and api_key= values and card-like digit runs. It also logs a user-supplied string that contains a newline and a fake error line.
import json import logging import re import sys PATTERNS = [ (re.compile(r"(?i)(token|password|api_key)=\S+"), r"\1=[redacted]"), (re.compile(r"(?<!\d)(?:\d[ -]?){12,15}\d(?!\d)"), "[card]"), ] class Redact(logging.Filter): def filter(self, record): text = record.getMessage() for pattern, repl in PATTERNS: text = pattern.sub(repl, text) record.msg, record.args = text, None return True class Json(logging.Formatter): def format(self, record): return json.dumps({"level": record.levelname, "msg": record.getMessage()})
secrets.py, part 1: the redaction filter and a JSON formatter
h = logging.StreamHandler(sys.stdout) h.setFormatter(Json()) h.addFilter(Redact()) log = logging.getLogger("pay") log.addHandler(h) log.setLevel(logging.INFO) log.info("login ok token=eyJhbGciOi9 user=asha") log.warning("charge failed for card 1234 5678 9012 3456") user_input = "asha\nERROR admin password reset" log.info("search for %s", user_input)
secrets.py, part 2: three log calls, including a newline in user input
{"level": "INFO", "msg": "login ok token=[redacted] user=asha"}
{"level": "WARNING", "msg": "charge failed for card [card]"}
{"level": "INFO", "msg": "search for asha\nERROR admin password reset"}Python 3.12.10. Deterministic.
The token and the card number are gone from the output. The third line shows log injection defeated: the user's newline and fake ERROR admin password reset text stayed inside one JSON string, with the newline escaped as \n. A text format that pasted the string in would have printed two lines, and the second would look like a real error. Notice also what the filter missed: password reset was not masked because only password= is matched. A filter is a net with holes, so keep secrets out at the source as well.