System Design

C14

Metrics and alerting

A fleet exports numbers every few seconds. The system stores them for months, draws dashboards in a second, and wakes someone only when users are hurt. The hard parts are series count, bytes per sample, long-range queries and alert noise.

Not startedSaved in this browser only.
  1. 1A series is a metric name plus labels. Cost grows with the number of series, so cardinality is the first thing to bound.
  2. 2Delta-of-delta timestamps and XOR values pack a regular, slowly changing series into about 1 to 2 bytes a sample.
  3. 3Rollup tiers of count, sum, min, max and last let a 7-day chart read hundreds of times fewer points with the same answer.
  4. 4Alert on error-budget burn over two windows, hold short spikes with "for", and let a router dedupe, group and route.
C14
    A

    The prompt

    as the interviewer says it
    "Design a system that ingests metrics from a fleet, stores them, serves dashboards, and fires alerts."
    questionanswer assumed
    How large is the fleet?20,000 hosts.
    Series per host?About 500: host metrics plus each service's.
    How often?Every 15 s.
    How long kept?Raw 15 days; 5 minute tier 90 days; 1 hour tier 2 years.
    Logs and traces?Out of scope; metrics only (O3).
    Alerts?Pages for user-facing symptoms; tickets for the rest.
    Exact or approximate?Exact sample values; percentiles from histograms.

    I confirm the fleet size, series per host, scrape interval, retention and who gets paged, because those set ingest rate, storage and alert design.

    B

    Requirements

    as numbers
    functional
    Ingest samples of named, labelled series.
    Query by label, over a range, at a step.
    Dashboards of many such queries.
    Alert rules on a schedule; route to people.
    non-functionaltarget
    Active series10 M
    Ingest≈ 667,000 samples/s
    Sample visible to queries< 1 min after the scrape
    7-day dashboardp99 < 1 s
    Page after errors start, 5% errors≤ 60 min × 14.4 ÷ 50 ≈ 17 min
    Page after a full outage≤ 60 min × 14.4 ÷ 1,000 ≈ 1 min
    Monitoring down unnoticednever: a dead man's switch

    Writes never block the fleet, a dashboard over 7 days answers in a second, and a page reaches someone within minutes of users being hurt.

    C

    Estimates

    the arithmetic, on the board
    quantityarithmeticresult
    Active series20,000 hosts × 50010 M
    Samples10 M ÷ 15 s≈ 667,000/s; × 3 replicas ≈ 2,000,000/s
    Raw, per series a day5760 samples × 2.57 B (lab mix)≈ 14.8 KB
    Raw, 15 days10 M × 14.8 KB × 15≈ 2.2 TB
    5 minute tier, 90 days10 M × 3.4 KB (lab) × 90≈ 3.1 TB
    1 hour tier, 2 years10 M × 331 B (lab) × 730≈ 2.4 TB
    Rule evaluations5,000 rules ÷ 60 s≈ 83 queries/s, steady

    Bytes per sample and tier sizes come from the lab fleet: 60 hosts, 240 series, 8 days at 30 s. A tier's size per series does not depend on the scrape interval. Method: R2.

    About 10 million series and 667,000 samples a second. At the lab's 2.57 bytes a sample, raw data is about 2.2 TB for 15 days; the tiers add 5.5 TB.

    D

    API

    write, read, rules, alerts
    callsuccesserrors
    GET /metrics (on each target)200 text samplestimeout → up = 0
    POST /api/v1/write (batch)204400 out of order, 429 series limit
    GET /api/v1/query_range?query=&start=&end=&step=200 series of points422, 503 too many samples
    PUT /api/v1/rules/{group}202400 bad expression
    POST /api/v2/alerts200400
    POST /api/v2/silences200 silence id400
    • A retried write batch is safe: a sample with the same series and timestamp is stored once.
    • Alerts post again every evaluation; the router treats a repeat as "still firing".

    Agents remote-write compressed batches. Dashboards call a range query with a step. Evaluators post alerts to the router, which dedupes them by label set.

    E

    Collection: pull or push

    who starts the transfer
    methodstatuswhy
    Pull: scrape /metricsApprovedTarget list from service discovery; up = 0 when one is silent.
    Push from each processShort jobs, NATA dead process sends nothing, which looks like no traffic.
    Agent per host, then remote writeApprovedScrapes locally, batches, buffers during an outage.
    Write straight to the storeSmall fleetA store slowdown pushes back on every host.
    Through a queueApprovedBursts and ingester restarts wait in the log (C13).
    • Counters only go up, so a lost scrape loses resolution, not the total.
    • Histograms export bucket counters; percentiles come from them at query time.

    I pull from long-running services, because the scraper then knows every target and a silent one shows as down. Short jobs push to a local agent.

    F

    Data model

    series, index, chunks, tiers
    one serieshttp_requests_total{service="checkout", host="checkout-01", code="500"} → id 3postings: label pair → sorted series ids__name__="http_requests_total"120 ids23671011…service="checkout"80 ids012345…code="500"60 ids3711151923…intersect, shortest list first: 60 ∩ 80 ∩ 120 → 20 series; then read only their chunks
    storekeyvalue
    Seriesname + sorted labelsSeries id
    Postingslabel name = valueSorted series ids
    Chunkseries id, start timeUp to 120 compressed samples
    Tier bucketseries id, tier, startcount, sum, min, max, last
    Blocktime rangeIndex and chunks of 2 hours, immutable
    Alert staterule, label setPending since, firing, last sent
    • The lab fleet has 240 series over 68 label pairs; its whole index is 4.3 KB.
    • A block holds its own index, so a query over old data opens only the blocks in its range.

    A series is a name plus labels, with an id. Postings map each label pair to series ids. Each series owns compressed chunks and rollup tiers.

    G

    The architecture

    click a step; its path lights up
    Hosts + agentscrape every 15 sQueuepartitioned by seriesIngestershead, chunks, WALObject storageblocks and tiersCompactormerge, downsampleDashboardsa chart, 120 pointsQuery frontendtier, split, cacheStore gatewayreads old blocksRule evaluator2 copiesAlert routerdedupe, group, route

    Step 1: Collect

    • The agent scrapes /metrics of every process on the host every 15 s.
    • Short jobs push to the agent, which then serves them like any target.
    • Each scrape adds up = 1 or 0, so a dead target is itself a signal.

    If it fails

    A target does not answer: up = 0 for that scrape, and an alert on up fires after its "for".

    Agents scrape and remote-write through a queue to ingesters. Ingesters keep recent chunks in memory and cut blocks to object storage. Queries pick a tier; evaluators alert through a router.

    H

    Capabilities used

    what each part gives you
    toolcapabilitywhat it gives this designalso used for
    IngesterDelta-of-delta and XOR chunksAbout 2.57 bytes a sample in the lab, against 16 for a plain pair.Column stores (B12)
    IngesterInverted index: label pair → series idsA query reads only the series it names.Search engines (B8)
    IngesterHead in memory with a write-ahead logFresh samples are queryable at once and survive a crash.Databases, LSM memtables
    CompactorRollups of count, sum, min, max, lastLong ranges read a tier and give exact averages and maxima.Analytics rollups
    Object storageCheap, durable blocksMonths of history without large disks on ingesters.Backups, data lakes (B9)
    QueuePartitioned, replayable logBursts wait; a restarted ingester replays from its offset.Event buses
    EvaluatorRules with "for"; burn rates over two windowsPage on user pain, not on noise.SLOs (O3)
    RouterDedupe by label set; group; repeat; routeMany alert instances become one message to the right people.Incident tools
    HyperLogLogApproximate distinct count in 12 KBCounts series per metric to spot a cardinality explosion early.Unique visitors (B10)

    Compressed chunks make samples cheap, postings make label queries cheap, tiers make long ranges cheap, and the router makes alerts few.

    I

    Deep dive: series and cardinality

    the cost that grows without warning
    labelstatusseries it multiplies by
    service, route, status codeApprovedTens to hundreds; a fixed set
    host, podChurn is boundedFleet size; every deploy makes new pods
    user_id, order_id, request_idNot approvedUnbounded; put these on traces and logs
    raw URL pathNot approvedUnbounded; use the route template
    error message textNot approvedUnbounded; use an error class
    lab: one metric + user_idresult
    Series for 10,000 values, 1 hour10,000
    Chunks and index1.68 MB + 0.29 MB
    Per series, 1 hour197 B before process overhead
    HyperLogLog estimate10,035 series in 12 KB
    Limit of 5,000 series5,000 new series rejected
    series ids and postingspseudo code
    ref(labels):                            // once per new series1
      key = metric name + sorted labels
      IF key is known: RETURN its id
      IF series count >= limit: REJECT2          // cardinality guard
      id = next id
      FOR EACH label pair p: postings[p].append(id)3
      RETURN id                                 // the scraper caches it
    
    select(matchers):
      lists = postings[m] FOR EACH matcher m
      sort lists, shortest first4
      RETURN intersection of the sorted lists   // one merge pass each
    1. 1The scraper keeps the id, so a known series costs no lookup on later samples.
    2. 2A limit per tenant turns an explosion into an error for one team, not an outage for all.
    3. 3Ids grow, so every list stays sorted by appending.
    4. 4The smallest list bounds the work. Checkout's failed requests: 60, then 80, then 120 ids.
    Tested source Go: ref · Go: select
    Go: refgo
    
    // Ref returns the id of the series with these labels, creating it and adding it to the
    // postings list of every label pair. A scraper keeps the id, so later samples skip the lookup.
    func (h *Head) Ref(ls Labels) (uint32, error) {
      key := ls.String()
      if id, ok := h.byKey[key]; ok {
        return id, nil
      }
      if h.MaxSeries > 0 && len(h.series) >= h.MaxSeries {
        h.Rejected++
        return 0, fmt.Errorf("%s: %w", key, ErrSeriesLimit)
      }
      id := uint32(len(h.series))
      h.series = append(h.series, &series{labels: ls, rollup: map[Res][]Bucket{}})
      h.byKey[key] = id
      for _, l := range ls {
        h.postings[l] = append(h.postings[l], id)
      }
      return id, nil
    }
    
    Go: selectgo
    
    // Select returns the ids of series that match every matcher. It intersects the matchers'
    // postings lists, shortest first; each list is sorted, so one merge pass per list is enough.
    func (h *Head) Select(ms []Matcher, st *QueryStats) []uint32 {
      lists := make([][]uint32, 0, len(ms))
      for _, m := range ms {
        lists = append(lists, h.postings[Label(m)])
      }
      slices.SortFunc(lists, func(a, b []uint32) int { return len(a) - len(b) })
      if len(lists) == 0 {
        return nil
      }
      out := slices.Clone(lists[0])
      for _, l := range lists {
        st.Postings = append(st.Postings, len(l))
      }
      for _, l := range lists[1:] {
        keep := out[:0]
        i := 0
        for _, id := range out {
          for i < len(l) && l[i] < id {
            i++
          }
          if i < len(l) && l[i] == id {
            keep = append(keep, id)
          }
        }
        out = keep
      }
      st.Series = len(out)
      return out
    }
    

    Cost grows with series, not samples. One user_id label with 10,000 values made 10,000 series in the lab, so I cap series per tenant and keep IDs out of labels.

    J

    Deep dive: compression

    bytes per sample, measured
    seriesplainvarint dod + 8 BGorilla chunk
    up constant16 B9 B0.42 B
    http_requests_total counter16 B9 B1.42 B
    node_cpu_util gauge, 2 decimals16 B9 B7.04 B
    whole fleet16 B2.57 B
    methodstatuswhy
    A row per sample in a databaseSmall fleetsRow and index overhead per sample (B12).
    Column encoding: delta, run lengthBatch analyticsByte-aligned; values still cost 8 bytes.
    Gorilla: delta of delta, XORApprovedBit-aligned; tuned for regular scrapes and slow values.
    Round values before storingPrecision to spareFewer changed bits in each XOR.

    Lab: 5,529,600 samples, 46,080 chunks of 120. Timestamps are regular; scrapers align them to the interval within a few milliseconds.

    append one sample to a chunkpseudo code
    append(t, v):                           // up to 120 samples a chunk1
      dod = (t - t_prev) - (t_prev - t_prev2)
      IF dod = 0: write 1 bit2                   // a regular scrape
      ELSE: write a prefix and dod in 14 to 64 bits
      x = bits(v) XOR bits(v_prev)3
      IF x = 0: write 1 bit                     // same value
      ELSE IF x fits the last window of changed bits:
        write the changed bits only4
      ELSE: write leading zeros, length, changed bits
    1. 1At a 30 s interval a chunk covers 1 hour. A query decodes whole chunks, so smaller chunks cost less to read but more in headers.
    2. 2Regular scrapes make the delta of delta 0, so a timestamp costs 1 bit.
    3. 3Close values share sign, exponent and high mantissa bits, so the XOR has long runs of zeros.
    4. 4Reusing the last window skips 11 bits of header when the change sits in the same place.
    Tested source Go: chunk append
    Go: chunk appendgo
    
    // Chunk holds up to ChunkSamples samples of one series, compressed as in the Gorilla paper.
    // Timestamps: the first in full, the first delta in 32 bits, then the delta of the delta in a
    // bucket of 1, 16, 19, 22 or 68 bits. Values: the first in full, then each XOR with the one
    // before: 1 bit when equal, else only the bits that changed.
    type Chunk struct {
      s         bstream
      n         int
      t, delta  int64
      v         float64
      lead, sig uint8 // the window of meaningful bits of the last XOR
      first     int64
    }
    
    // Append adds a sample. Timestamps are milliseconds and must increase.
    func (c *Chunk) Append(t int64, v float64) {
      switch c.n {
      case 0:
        c.first = t
        c.s.writeBits(uint64(t), 64)
        c.s.writeBits(math.Float64bits(v), 64)
      case 1:
        c.delta = t - c.t
        c.s.writeBits(uint64(c.delta), 32)
        c.appendValue(v)
      default:
        d := t - c.t
        dod := d - c.delta
        switch {
        case dod == 0:
          c.s.writeBit(false) // a regular scrape: 1 bit
        case -8192 <= dod && dod <= 8191:
          c.s.writeBits(0b10, 2)
          c.s.writeBits(uint64(dod)&(1<<14-1), 14)
        case -65536 <= dod && dod <= 65535:
          c.s.writeBits(0b110, 3)
          c.s.writeBits(uint64(dod)&(1<<17-1), 17)
        case -524288 <= dod && dod <= 524287:
          c.s.writeBits(0b1110, 4)
          c.s.writeBits(uint64(dod)&(1<<20-1), 20)
        default:
          c.s.writeBits(0b1111, 4)
          c.s.writeBits(uint64(dod), 64)
        }
        c.delta = d
        c.appendValue(v)
      }
      c.t, c.v = t, v
      c.n++
    }
    
    func (c *Chunk) appendValue(v float64) {
      x := math.Float64bits(v) ^ math.Float64bits(c.v)
      if x == 0 {
        c.s.writeBit(false) // same value as before: 1 bit
        return
      }
      c.s.writeBit(true)
      lead, trail := uint8(bits.LeadingZeros64(x)), uint8(bits.TrailingZeros64(x))
      lead = min(lead, 31) // stored in 5 bits
      if c.sig != 0 && lead >= c.lead && trail >= 64-c.lead-c.sig {
        c.s.writeBit(false) // the changed bits fit the last window: reuse it
        c.s.writeBits(x>>(64-c.lead-c.sig), int(c.sig))
        return
      }
      sig := 64 - lead - trail
      c.s.writeBit(true)
      c.s.writeBits(uint64(lead), 5)
      c.s.writeBits(uint64(sig)&63, 6) // 64 is stored as 0
      c.s.writeBits(x>>trail, int(sig))
      c.lead, c.sig = lead, sig
    }
    

    Regular timestamps cost 1 bit, and an unchanged value 1 bit. The lab fleet averaged 2.57 bytes a sample: 0.42 for a constant, 1.42 for a counter, 7.04 for a noisy gauge.

    K

    Deep dive: downsampling and retention

    tiers for long ranges
    tierkeptlab size, whole fleetper series a day
    raw, 30 s15 days14.2 MB7.4 KB
    5 minutes90 days6.6 MB3.4 KB
    1 hour2 years0.64 MB331 B
    7-day CPU by servicepoints readtime
    raw samples1,209,600254.7 ms
    5m tier120,9603.9 ms
    1h tier10,080366 µs
    • A chart is about 120 points wide. Reading more points than that draws nothing extra.
    • Keep min and max: an average tier hides a 3-minute spike, but its max shows it.
    rollups and the querypseudo code
    on every sample (t, v):
      FOR EACH tier IN (5 min, 1 hour):
        b = bucket of tier at floor(t / tier)
        b.count += 1; b.sum += v
        b.min = min(b.min, v); b.max = max(b.max, v)
        b.last = v1                              // for counters
    
    query(range, step, tier):
      read buckets of the tier, or raw samples
      avg      = sum of sums / sum of counts    // never an average of averages2
      max      = max of maxes
      increase = last - previous step's last3
    1. 1A counter's increase over a step is last minus the step before's last, so a tier serves rates too.
    2. 2The lab checks that every tier gives the same averages and counter increases as raw samples.
    3. 3A counter reset after a restart shows as a drop; a real engine adds the value before the reset back.
    Tested source Go: append and roll up · Go: query
    Go: append and roll upgo
    
    // Append adds a sample to a series: into the open chunk, cutting a new chunk every
    // ChunkSamples, and into the current bucket of each rollup tier.
    func (h *Head) Append(id uint32, t int64, v float64) {
      s := h.series[id]
      if len(s.chunks) == 0 || s.chunks[len(s.chunks)-1].Len() >= ChunkSamples {
        s.chunks = append(s.chunks, &Chunk{})
      }
      s.chunks[len(s.chunks)-1].Append(t, v)
      for _, r := range Tiers {
        start := t - t%int64(r)
        bs := s.rollup[r]
        if n := len(bs); n > 0 && bs[n-1].T == start {
          bs[n-1].add(one(Sample{t, v}))
          continue
        }
        b := one(Sample{t, v})
        b.T = start
        s.rollup[r] = append(bs, b)
      }
    }
    
    Go: querygo
    
    // Query selects series, reads them at a resolution, cuts [from, to) into steps, and combines per
    // group of the `by` label. The step is never finer than the resolution read.
    func (h *Head) Query(ms []Matcher, by string, agg Agg, from, to, step int64, res Res) (map[string][]Point, QueryStats, error) {
      var st QueryStats
      step = max(step, int64(res))
      n := int((to - from) / step)
      type acc struct {
        b   []Bucket
        inc []float64
      }
      groups := map[string]*acc{}
      for _, id := range h.Select(ms, &st) {
        pts, err := h.read(id, from, to, res, &st)
        if err != nil {
          return nil, st, err
        }
        per := make([]Bucket, n) // this series, one bucket per step
        for _, p := range pts {
          if i := int((p.T - from) / step); i < n {
            per[i].add(p)
          }
        }
        g := h.series[id].labels.Get(by)
        a := groups[g]
        if a == nil {
          a = &acc{b: make([]Bucket, n), inc: make([]float64, n)}
          groups[g] = a
        }
        for i := range per {
          if per[i].Count == 0 {
            continue
          }
          if i > 0 && per[i-1].Count > 0 {
            a.inc[i] += per[i].Last - per[i-1].Last
          }
          if a.b[i].Count == 0 {
            a.b[i] = per[i]
          } else {
            a.b[i].Count += per[i].Count
            a.b[i].Sum += per[i].Sum
            a.b[i].Max = math.Max(a.b[i].Max, per[i].Max)
          }
        }
      }
      out := map[string][]Point{}
      for g, a := range groups {
        for i := range n {
          t := from + int64(i)*step
          switch {
          case a.b[i].Count == 0:
          case agg == Avg:
            out[g] = append(out[g], Point{t, a.b[i].Sum / float64(a.b[i].Count)})
          case agg == Max:
            out[g] = append(out[g], Point{t, a.b[i].Max})
          case agg == Increase && i > 0:
            out[g] = append(out[g], Point{t, a.inc[i]})
          }
        }
      }
      return out, st, nil
    }
    

    I keep raw samples for 15 days, a 5 minute tier for 90 days and a 1 hour tier for 2 years. Each bucket keeps count, sum, min, max and last, so every aggregate stays exact.

    L

    See it: one query, three resolutions

    recorded from the lab TSDB
    query
    range
    resolution
    max(node_cpu_util{host="checkout-01"})
    postings read
    4 ∩ 60
    series matched
    1
    chunks decoded
    24
    points read
    2,880
    step
    12 min
    points returned
    120
    time, this laptop
    686 µs
    0501001 d agonow · CPU %
    raw, 30 s2,880 points read5 min tier288 points read1 hour tier24 points read

    The fleet: 60 hosts in 3 services, 8 days at 30 s. "Now" is 15:00 on the incident day, an hour after checkout's errors began. Times are medians on one laptop core.

    A 7-day chart from the 1 hour tier read 10,080 points instead of 1,209,600. A 1-hour chart of the incident needs raw samples; the hourly tier gives one point.

    M

    Deep dive: alerts

    the recorded incident
    incident day, 13:40 to 15:40 · rules evaluated every minutecheckout errors0 to 6%SLO allows 0.1%hot checkout hostsHostCPUHigh · ticketburn 14.4× · pageburn 6× · pageburn 1× · ticketnotifications123456713:4014:0014:2014:4015:0015:2015:401 14:11 ticket queue: HostCPUHigh, 6 hosts2 14:17 on-call pager: ErrorBudgetBurn page, fast3 14:40 ticket queue: HostCPUHigh, resolved4 14:41 on-call pager: ErrorBudgetBurn page, slow5 14:44 ticket queue: ErrorBudgetBurn ticket6 14:48 on-call pager: ErrorBudgetBurn page, fast, resolved7 15:11 on-call pager: ErrorBudgetBurn page, slow, resolved
    rule stylestatusin the lab
    Errors over the SLO for 1 minuteNot approved9.43 pages a quiet day
    Threshold with "for: 5m"Causes, as tickets3-minute spike held; fired at 14:10
    Burn rate, 1 h and 5 min windowsApprovedpaged 16 min in; 0 quiet pages
    Page on CPU, disk, memoryNot approvedCauses; users may be fine
    router stepin the incident
    Alert instances received, 2 evaluators640
    Pages sent (firing)2
    Tickets sent (firing)2

    SLO 99.9%. Rules from the SRE Workbook, as on O3. Group wait 30 s, group interval 5 min, repeat 4 h.

    evaluate, then routepseudo code
    every minute, FOR EACH rule:
      FOR EACH series where value > threshold:
        IF pending for >= rule.for: FIRING
        ELSE: PENDING                           // short spikes stop here1
      burn = error ratio / (1 - SLO)
      page IF burn > 14.4 over 1 h AND over 5 min2
    
    router.receive(alerts from every evaluator):
      drop duplicates by fingerprint3 (the label set)
      group by (alertname, service)4
      new group:     notify after group_wait
      changed group: notify after group_interval
      same group:    repeat after repeat_interval
      route by severity5: page -> on-call, ticket -> queue
    1. 1search-03 ran hot for 3 minutes; it was pending 3 minutes and never fired.
    2. 2The long window proves the burn is real. The short one stops the page soon after the errors stop.
    3. 3Two evaluators send every alert; one notification goes out.
    4. 46 hot checkout hosts became one ticket listing all 6.
    5. 5Pages wake a person; tickets wait for working hours.
    Tested source Go: threshold rule · Go: router
    Go: threshold rulego
    
    // Eval runs the rule at time t, as the rule evaluator does every interval. A series above the
    // threshold is pending; once it has stayed above for For, it fires. A value at or below the
    // threshold resets it.
    func (r ThresholdRule) Eval(h *Head, t int64, state map[uint32]*RuleState) ([]Alert, error) {
      vals, err := h.Instant(r.Matchers, t)
      if err != nil {
        return nil, fmt.Errorf("rule %s: %w", r.Name, err)
      }
      var out []Alert
      for id, v := range vals {
        s := state[id]
        if s == nil {
          s = &RuleState{}
          state[id] = s
        }
        if v <= r.Threshold {
          *s = RuleState{}
          continue
        }
        if s.Since == 0 {
          s.Since = t
        }
        s.Firing = t-s.Since >= r.For
        if s.Firing {
          ls := h.Labels(id)
          out = append(out, Alert{Name: r.Name, Service: ls.Get("service"), Host: ls.Get("host"), Severity: r.Severity})
        }
      }
      slices.SortFunc(out, func(a, b Alert) int { return strings.Compare(a.Fingerprint(), b.Fingerprint()) })
      return out, nil
    }
    
    Go: routergo
    
    // Tick takes every alert that every evaluator sent at time t and returns the notifications due.
    // Alerts with one fingerprint count once, however many evaluators sent them. A new group waits
    // GroupWait; a changed group waits GroupInterval since its last message; an unchanged group
    // repeats after RepeatInterval. A group whose alerts all stopped gets one resolved message.
    func (rt *Router) Tick(t int64, batches ...[]Alert) []Notification {
      if rt.groups == nil {
        rt.groups = map[string]*group{}
      }
      now := map[string]map[string]bool{}
      for _, b := range batches {
        rt.Received += len(b)
        for _, a := range b {
          k := rt.key(a)
          if now[k] == nil {
            now[k] = map[string]bool{}
          }
          now[k][a.Fingerprint()] = true // deduplicated here
        }
      }
      for k, fps := range now {
        g := rt.groups[k]
        if g == nil || !g.open {
          g = &group{first: t, firing: map[string]bool{}, notified: map[string]bool{}, open: true}
          rt.groups[k] = g
        }
        g.firing = fps
      }
      var out []Notification
      keys := make([]string, 0, len(rt.groups))
      for k := range rt.groups {
        keys = append(keys, k)
      }
      sort.Strings(keys)
      for _, k := range keys {
        g := rt.groups[k]
        if !g.open {
          continue
        }
        if now[k] == nil {
          g.firing = map[string]bool{}
        }
        changed := !mapsEqual(g.firing, g.notified)
        due := false
        switch {
        case g.sent == 0:
          due = t-g.first >= rt.Route.GroupWait
        case changed:
          due = t-g.sent >= rt.Route.GroupInterval
        default:
          due = t-g.sent >= rt.Route.RepeatInterval
        }
        if !due || (g.sent == 0 && len(g.firing) == 0) {
          if g.sent == 0 && len(g.firing) == 0 {
            g.open = false // it stopped before anyone was told
          }
          continue
        }
        n := Notification{T: t, Receiver: rt.Receivers[strings.SplitN(k, "/", 2)[0]], Group: k, Resolved: len(g.firing) == 0}
        for fp := range g.firing {
          n.Firing = append(n.Firing, fp)
        }
        sort.Strings(n.Firing)
        out = append(out, n)
        g.sent, g.notified = t, g.firing
        if n.Resolved {
          g.open = false
        }
      }
      return out
    }
    

    The fast burn rule paged 16 minutes into a 5% error spike. 6 hot hosts made one ticket. In the quiet week before, a naive threshold would have paged 9.43 times a day.

    N

    Failure cases

    what breaks, and what still works
    eventresultwhy it is safesaved by
    An ingester crashesIts head in memory is gone.It replays its WAL or the queue; 2 other replicas answer reads.WAL, 3 replicas
    Ingest is slower than the fleetLag grows.The queue holds the samples; alert on lag in time.Queue
    A deploy adds a user_id labelSeries explode.The tenant's series limit rejects new series; others are untouched.Series limit
    A target diesIts samples stop.The scrape fails and up = 0 fires its own alert.Pull, up
    A rule evaluator diesHalf the copies stop.The other copy sends the same alerts; the router dedupes.2 evaluators
    The whole alert path is downNothing pages.A dead man's switch alert stops arriving at an outside service, which pages.Outside check
    A heavy query over all seriesMemory runs out on the query path.Limits on series and samples per query refuse it early.Query limits
    An incident trips 50 rulesA storm of alerts.Grouping, and inhibition of cause alerts while a symptom page fires.Router
    O

    Scale ladder

    start simple; climb only on a signal
    Each step adds one component1One server2+ HA pair3+ sharded scrapes4+ queue, store5+ regionsmore load →
    Samples per second against this prompt's demand10k100k1M10M100MDemand: ingest: 666,667 samples per secondDemand: ingest666,667Demand: 3 replicas: 2,000,000 samples per secondDemand: 3 replicas2,000,000Lab head, one core: 6,040,000 samples per secondLab head, one core6,040,000samples per second, log scale
    stepaddit handlesmove up when you see
    1One Prometheus server, local disk, one alert router.A team or a small fleet; the lab head appends 6.0 M samples a second on one core.One restart leaves no alerts; active series fill its memory.
    2A pair of servers scraping the same targets; a router cluster.One server can die; the router dedupes both copies' alerts.One machine's memory cannot hold every series.
    3Shard scrapes by team or by hash of target.Series spread over servers; each server stays small.Queries need a global view; retention passes local disks.
    4Remote write through a queue to ingesters, object storage and tiers.10 M series and months of history; queries across the fleet.Regions far apart, or a region outage must not blind the others.
    5A stack per region; a global query layer fans out.Local ingest and alerting keep working when another region fails.Top of the ladder.

    The ingest rate is the lab head on one laptop core: chunks and two tiers, no WAL and no network. A real ingester spends more per sample on both. Read it as an order of magnitude.

    I start with one Prometheus server and an alert router. I add a high-availability pair, then shard scrapes, and move to a horizontally scaled store when one machine's series or retention run out.

    P

    Follow-ups

    what the interviewer asks next
    questionanswerdeeper
    How do you compute p99 latency across hosts?Export histograms, sum the bucket counters across hosts, then take the quantile. Averaging each host's p99 gives a wrong number.O3
    What is an SLO burn rate?The error ratio divided by the ratio the SLO allows. A burn of 14.4 spends 2% of a 30-day budget in one hour.O3
    Why a queue in front of the store?It absorbs bursts and ingester restarts, and a replay rebuilds a lost head. Partition by series hash, so one series stays in order.C13
    How do you count distinct series cheaply?A HyperLogLog sketch per metric gives the count within about 1% in 12 KB, and sketches merge across ingesters.B10
    Ad hoc analysis over a year of events?That is a column store's job, with rollups on insert. Keep metrics for dashboards and alerts.B12
    How do ingesters split the series?A hash ring of series ids with 3 replicas each; a new ingester takes a slice from every other one.X2
    How long until a dead host is noticed?One scrape interval for up = 0, plus the rule's "for". Membership protocols detect faster inside a cluster.X6
    Q

    Drill

    predict, then reveal

    0 of 10 known

    1. A team adds a user_id label to a request counter. What happens?

    2. Why does a constant series cost under half a byte a sample?

    3. Why does a CPU gauge cost far more than a counter?

    4. A 7-day dashboard is slow. What do you change first?

    5. Why does a rollup keep sum and count instead of the average?

    6. Why does an hourly chart hide the incident?

    7. Why not page whenever errors pass the SLO's 0.1% for a minute?

    8. What does "for: 5m" do to a 3-minute CPU spike?

    9. 6 hosts run hot at once, and 2 evaluators send every alert. How many tickets?

    10. Pull or push for a fleet of long-running services?

    R

    Numbers to say

    measured, derived or cited
    demand
    10 M series, about 667,000 samples a second.
    bytes
    2.57 B a sample for the lab mix; 0.42 B for a constant; 16 B plain.
    storage
    Raw 15 days ≈ 2.2 TB; tiers ≈ 5.5 TB.
    tiers
    7-day chart: 1,209,600 points raw, 10,080 from the 1 hour tier.
    cardinality
    10,000 user IDs: 10,000 series from one.
    alerts
    Fast burn paged 16 min into a 5% spike; a naive rule pages 9.43 times a quiet day.
    burn 14.4
    Spends 2% of a 30-day budget in 1 hour (SRE Workbook).

    Fleet runs are seeded and repeat exactly. Times and the ingest rate come from one laptop core shared with other jobs.