Low-Latency Serving: Caches, Data APIs and Real-Time OLAP
Serve a customer-facing usage chart that must be fresh within a minute and fast for many users: roll events up as they arrive, put a small data API with tenant isolation and a versioned cache in front, and see when a real-time OLAP store such as ClickHouse, Pinot or Druid is the next step.
Contentsand lesson path
On this page
- The problem
- Step 1: Decide what the chart reads
- Step 2: Load three minutes of events, then retry one
- Step 3: Put a data API in front, with a cache
- Step 4: Check tenant isolation
- Step 5: New data arrives
- Step 6: When to move to a real-time OLAP store
- Check your understanding
- Apply it
- Review prompt
Lessons of Data Serving & BI
- Who Consumes Data and How It Reaches Them Concept · 20 min
- One Definition per Metric: Building a Semantic Layer Worked example · 25 min
- Lab: A Fast Dashboard That Respects Access Rules Lab · 30 min
- Lab: Reverse ETL from a Mart to an Operational Tool Lab · 25 min
- Low-Latency Serving: Caches, Data APIs and Real-Time OLAP Worked example · 20 min
- Check: Choose and Defend a Serving Path Knowledge check · 8 questions
What you will learn
- Choose a serving path for a consumer (warehouse query, cached extract, data API, real-time OLAP store or feature table) from its freshness, latency, concurrency and cost requirements.
01. The problem
A software company sells an API. Its customers, called tenants because many of them share one system, want a chart in the product that shows how many calls they made per minute over the last hour. Product has written the requirements down:
- Freshness: a call should appear in the chart within about a minute.
- Latency: the chart is part of the app, so each request should answer in well under a second, even at the busiest time.
- Concurrency: thousands of users may have the page open, and the chart refreshes every minute.
- Isolation: a tenant must never see another tenant's numbers.
- Cost: the cost of serving must not grow with every page view.
The raw events already land in the warehouse every night for analysts. Serving the chart straight from the warehouse fails twice: a nightly load is far from one-minute freshness, and one warehouse query per page view is slow and costly at that concurrency, because warehouses are built for fewer, heavier queries. A nightly BI extract fails on freshness too. This worked example builds the serving path step by step, small enough to run on a laptop, and then shows which production tool does each job.
02. Step 1: Decide what the chart reads
The chart needs one number per tenant per minute. Counting raw events for each request repeats the same work thousands of times, so do it once, when the events arrive. That is a rollup: a table at the grain the reader needs, here one row per tenant and minute. Each new batch of events adds to the rows for its minute. A request then reads at most 60 small rows instead of hundreds of thousands of events.
Adding to a rollup has a trap. If a batch is loaded twice, for example when a job is retried after a timeout, every count for that minute doubles. The rollup is fast because it forgets the individual events, so it cannot tell a retry from new data. The load must therefore record which batches it has applied, and refuse a batch it has seen.
The example uses SQLite from the Python standard library, so it needs nothing beyond Python 3.10 or later; it was run with Python 3.12 and SQLite 3.53. WAL mode (write-ahead logging) lets the API read while a load is writing. Create a folder for this lesson with mkdir usage-serving && cd usage-serving, and save every file in it.
"""Load one minute of API-call events and fold it into a per-minute rollup."""
import random
import sqlite3
import sys
from collections import Counter
from datetime import datetime, timedelta
batch = int(sys.argv[1]) # 1, 2, 3 ... one batch per minute
rng = random.Random(batch)
minute = datetime(2026, 11, 16, 9, 0) + timedelta(minutes=batch)
events = [(rng.choice(["acme", "globex", "initech"]),
(minute + timedelta(seconds=rng.randrange(60))).isoformat(),
rng.choice(["/search", "/export", "/login"]))
for _ in range(rng.randint(4000, 6000))]
con = sqlite3.connect("serving.db")
con.execute("pragma journal_mode = wal") # readers keep working during a load
con.executescript("""
create table if not exists events (tenant text, ts text, path text);
create table if not exists usage_minute (
tenant text, minute text, calls integer, primary key (tenant, minute));
create table if not exists load_log (batch integer primary key, events integer);
""")
if con.execute("select 1 from load_log where batch = ?", [batch]).fetchone():
sys.exit(f"batch {batch} is already loaded; adding it again would double-count")
counts = Counter((tenant, ts[:16]) for tenant, ts, _ in events) # minute = ts[:16]
with con: # one transaction: all of it or none
con.executemany("insert into events values (?, ?, ?)", events)
# Add this batch's counts to the rollup: update the row if it exists, else insert.
con.executemany("""
insert into usage_minute values (?, ?, ?)
on conflict (tenant, minute) do update set calls = calls + excluded.calls
""", [(tenant, minute, n) for (tenant, minute), n in counts.items()])
con.execute("insert into load_log values (?, ?)", [batch, len(events)])
raw, rolled = con.execute("select (select count(*) from events),"
" (select count(*) from usage_minute)").fetchone()
print(f"batch {batch}: {len(events)} events loaded;"
f" events table {raw} rows, rollup {rolled} rows")03. Step 2: Load three minutes of events, then retry one
for batch in 1 2 3; do python3 ingest.py $batch; donebatch 1: 4275 events loaded; events table 4275 rows, rollup 3 rows
batch 2: 5957 events loaded; events table 10232 rows, rollup 6 rows
batch 3: 4487 events loaded; events table 14719 rows, rollup 9 rowsFourteen thousand events became nine rollup rows: three tenants times three minutes. Now pretend the scheduler retries batch 3.
python3 ingest.py 3; echo "exit code: $?"batch 3 is already loaded; adding it again would double-count
exit code: 1The check works because the batch number and the rollup change are written in one transaction: either both are stored or neither is. The batch number is also the primary key of load_log, a second guard: without the check, the duplicate insert would fail and roll the whole transaction back. Real streaming systems solve the same problem with offsets, deduplication keys or idempotent writes, and you should find out which one your tool uses before you trust its totals.
04. Step 3: Put a data API in front, with a cache
Applications should not hold database credentials or write SQL for each chart. A data API is a small service that answers a fixed set of questions over HTTP, checks who is asking, and limits what they can ask for. Here it has one endpoint, /usage?minutes=N, and it accepts at most 1,440 minutes so that nobody can request an unbounded scan.
The API caches each answer, and the interesting part is the cache key: tenant, window and data version. The data version is the last batch number in load_log. Checking it costs one tiny query, and when a new batch lands the version changes, so every old entry stops matching. As long as every change goes through ingest.py and batch numbers only grow, no stale entry is served and no expiry time has to be guessed. A late batch with a lower number than the newest one would not change max(batch), so a real service uses a counter that grows with every applied load, such as an auto-increment load id, rather than the batch number. Without the version in the key, the cache would need a time-to-live: too short and it saves little, too long and charts lag behind the data. A real service also bounds the cache's size, for example by evicting the least recently used entries.
"""A read-only usage API: one tenant per token, results cached until the next load."""
import json
import sqlite3
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
# In production the token is checked by your identity provider; here it is a dict.
TOKENS = {"token-acme": "acme", "token-globex": "globex"}
cache = {} # (tenant, minutes, data version) -> body
def read_usage(tenant, minutes):
con = sqlite3.connect("file:serving.db?mode=ro", uri=True)
try:
version = con.execute("select max(batch) from load_log").fetchone()[0]
key = (tenant, minutes, version)
if key in cache:
return cache[key], "hit"
rows = con.execute("""
select minute, calls from usage_minute where tenant = ?
order by minute desc limit ?""", [tenant, minutes]).fetchall()
finally:
con.close()
body = {"tenant": tenant, "data_version": version,
"points": [{"minute": m, "calls": c} for m, c in reversed(rows)]}
cache[key] = body
return body, "miss"
class Handler(BaseHTTPRequestHandler):
def reply(self, status, body, cache_status="none"):
data = json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("X-Cache", cache_status)
self.end_headers()
self.wfile.write(data)
def do_GET(self):
url = urlparse(self.path)
if url.path != "/usage":
return self.reply(404, {"error": "not found"})
token = self.headers.get("Authorization", "").removeprefix("Bearer ")
tenant = TOKENS.get(token)
if tenant is None:
return self.reply(401, {"error": "unknown token"})
try:
minutes = int(parse_qs(url.query).get("minutes", ["60"])[0])
except ValueError:
return self.reply(400, {"error": "minutes must be a whole number"})
if not 1 <= minutes <= 1440:
return self.reply(400, {"error": "minutes must be between 1 and 1440"})
body, status = read_usage(tenant, minutes)
self.reply(200, body, status)
def log_message(self, *args):
pass
if __name__ == "__main__":
print("usage API on http://127.0.0.1:8767", flush=True)
ThreadingHTTPServer(("127.0.0.1", 8767), Handler).serve_forever()"""Call the usage API as a tenant and print the answer compactly."""
import json
import sys
import urllib.error
import urllib.request
token, minutes = sys.argv[1], sys.argv[2]
req = urllib.request.Request(f"http://127.0.0.1:8767/usage?minutes={minutes}",
headers={"Authorization": f"Bearer {token}"})
try:
with urllib.request.urlopen(req, timeout=5) as r:
body, status, cache = json.load(r), r.status, r.headers["X-Cache"]
except urllib.error.HTTPError as e:
body, status, cache = json.load(e), e.code, e.headers["X-Cache"]
if status != 200:
sys.exit(f"{status}: {body['error']}")
print(f"{status} {body['tenant']} version={body['data_version']} cache={cache}")
for point in body["points"]:
print(f" {point['minute']} {point['calls']:>5}")cd usage-serving && python3 api.py
python3 show.py token-acme 3
python3 show.py token-acme 3200 acme version=3 cache=miss
2026-11-16T09:01 1438
2026-11-16T09:02 2010
2026-11-16T09:03 1483
200 acme version=3 cache=hit
2026-11-16T09:01 1438
2026-11-16T09:02 2010
2026-11-16T09:03 148305. Step 4: Check tenant isolation
The tenant comes from the token, never from the request. Ask as another tenant, with a token the API does not know, and finally with no token but a tenant parameter in the URL, the way an attacker might try.
python3 show.py token-globex 3
python3 show.py wrong-token 3
curl -s "http://127.0.0.1:8767/usage?minutes=3&tenant=globex"; echo200 globex version=3 cache=miss
2026-11-16T09:01 1448
2026-11-16T09:02 1976
2026-11-16T09:03 1556
401: unknown token
{"error": "unknown token"}Globex gets its own numbers and a cache miss, because its key differs. The tenant parameter does nothing: the API never reads it. Keep the tenant in the cache key and in the WHERE clause, and derive both from the authenticated identity.
06. Step 5: New data arrives
Load the next minute and ask again as Acme. The answer is a miss with version 4, and it already contains 09:04. Freshness is now the time from an event to the end of its batch's load; the cache adds no delay, because a new version turns the next request into a miss.
python3 ingest.py 4
python3 show.py token-acme 3batch 4: 4483 events loaded; events table 19202 rows, rollup 12 rows
200 acme version=4 cache=miss
2026-11-16T09:02 2010
2026-11-16T09:03 1483
2026-11-16T09:04 1518Stop the API with Ctrl+C when you have finished.
07. Step 6: When to move to a real-time OLAP store
SQLite and one Python process are enough to learn the pattern, not to serve thousands of tenants. A real-time OLAP store does the same jobs at scale. OLAP (online analytical processing) means fast aggregations over many rows. These stores read events straight from a stream such as Kafka, store data in columns, and pre-aggregate as data arrives:
- ClickHouse has incremental materialized views: a query that runs on each inserted block and writes its result into a target table, often a
SummingMergeTreeorAggregatingMergeTreetable that combines rows with the same key. - Apache Druid can roll data up at ingestion time, combining events with the same dimensions and time bucket into one row. You lose the individual events in exchange.
- Apache Pinot offers a star-tree index that stores pre-aggregated results across several columns.
The sketch below shows the ClickHouse version of steps 1 and 3. It was not run for this lesson. Note the last query: ClickHouse sums rows with the same key when it merges parts in the background, and merges happen at unpredictable times, so a query must still sum() and GROUP BY to get the complete total.
CREATE TABLE events (tenant String, ts DateTime, path String)
ENGINE = MergeTree ORDER BY (tenant, ts);
CREATE TABLE usage_minute (tenant String, minute DateTime, calls UInt64)
ENGINE = SummingMergeTree ORDER BY (tenant, minute);
CREATE MATERIALIZED VIEW usage_minute_mv TO usage_minute AS
SELECT tenant, toStartOfMinute(ts) AS minute, count() AS calls
FROM events GROUP BY tenant, minute;
SELECT minute, sum(calls) AS calls FROM usage_minute
WHERE tenant = 'acme' GROUP BY minute ORDER BY minute DESC LIMIT 60;Use these signals to choose. If the consumer is a person exploring data, with few concurrent users and day-old data, query the warehouse. If many people view the same charts, use a cached extract or a pre-aggregate behind BI. If an application needs fixed questions answered for many users, put a data API in front of a rollup or a key-value store, and move to a real-time OLAP store when the data or the concurrency outgrows a single database. A machine learning model that needs a few values per customer within milliseconds needs a feature table in an online store: precomputed values looked up by key, with an offline copy that is correct at each point in time for training.
08. Check your understanding
09. Apply it
The skill practice asks for a one-page decision record choosing the serving path for a customer-facing usage chart. Use this worked example as its evidence:
- State the requirements as numbers (freshness, latency, peak concurrency, cost limit, isolation), and reject the warehouse and the nightly extract with one sentence each.
- Describe the rollup grain, how retries are made safe, and how the cache key is built.
- Name the point at which you would move to ClickHouse, Pinot or Druid, and what you would measure to decide.
10. Review prompt
Without looking back, explain: why a warehouse query per page view does not fit a customer-facing chart; what a rollup is and why a retried batch can corrupt it; why the data version belongs in the cache key; how the API keeps tenants apart; and what a real-time OLAP store adds, including why a SummingMergeTree query still needs sum().
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.