AW Dev Rethought

โœ‚๏ธ Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away - Antoine de Saint-Exupรฉry

โš™๏ธ Python Backend Patterns โ€” Caching Pattern ๐Ÿ


Description:

A support team opens its dashboard twice. Both requests need the number of open tickets in the north branch. The first request scans a ticket table. The second could reuse the number the service just calculated. How long should it trust that number?


Put the cache beside the read path

In cache-aside, the service owns the lookup. It checks a key, returns the value on a fresh hit, and queries the underlying store on a miss. After the query succeeds, it stores the result with an expiration time.

Here the operation is always โ€œcount open tickets,โ€ so the branch is enough to identify a result. If users could choose a status filter, that filter would also belong in the key. User-specific results would need their access scope represented too.

entry = self.cache.get(branch)
if entry is not None:
    count, expires_at = entry
    if self.clock() < expires_at:
        return count

count = self.store.count_open(branch)
self.cache[branch] = (count, self.clock() + self.ttl)
return count

The strict comparison makes the entry expire at the deadline. The service checks for a missing entry explicitly so it can cache a count of zero.


Follow the north branch through five reads

The example begins with 60,000 tickets across two branches. North has 10,000 open tickets. We advance the freshness clock explicitly so the example runs without waiting 30 seconds.

Time Event before the read Count returned Cumulative count queries
0 s Cache is empty 10,000 1
1 s Same branch requests the count again 10,000 1
10 s An outside writer adds an open ticket 10,000 (stale) 1
30 s The original entry reaches its deadline 10,001 2
31 s The service commits another ticket and evicts the key 10,002 3

Expiry is checked on read. A hit leaves the original deadline in place. For writes that go through the service, invalidate after the database commit so the next read can fetch the updated value.


What did the shorter path save?

The script also uses a real performance timer to measure 101 direct reads and 101 warm reads, alternating their order. Both paths return the same count. On the recorded run, the median direct SQLite count took 2.322 ms and the median in-process cache hit took 0.209 ยตs. The benchmark excludes initial population and network time. It uses an in-memory SQLite table without an index on the filter columns. An indexed query, a different table size, or a remote cache changes the comparison.


Where this version fits

A 30-second lifetime buys fewer queries at the cost of potentially old counts after an outside write. Choose that lifetime based on what the caller can tolerate. This demo has a fixed set of branches, one process, and sequential requests. Multiple workers would keep separate copies. Concurrent misses could repeat the query, and a read racing a write could repopulate an old count. Those cases need an explicit coordination strategy if freshness matters.

Run the example: python3 caching_pattern.py. It checks the five-read trace and prints your own timings.


Code Snippet:

class TicketStore:
    def __init__(self, db):
        self.db = db
        self.reads = 0

    def count_open(self, branch):
        self.reads += 1
        return self.db.execute(
            "SELECT count(*) FROM tickets WHERE branch = ? AND status = 'open'",
            (branch,),
        ).fetchone()[0]

    def add_open(self, branch):
        with self.db:
            self.db.execute("INSERT INTO tickets VALUES (?, 'open')", (branch,))


class Dashboard:
    """Sequential, process-local cache for a fixed set of branch IDs."""
    def __init__(self, store, ttl=30, clock=monotonic):
        self.store = store
        self.ttl = ttl
        self.clock = clock
        self.cache = {}

    def open_count(self, branch):
        # The same branch always sees the same aggregate in this fixture.
        entry = self.cache.get(branch)
        if entry is not None:
            count, expires_at = entry
            if self.clock() < expires_at:
                return count  # Zero is a valid cached count.

        count = self.store.count_open(branch)
        self.cache[branch] = (count, self.clock() + self.ttl)
        return count

    def add_open(self, branch):
        self.store.add_open(branch)  # The transaction commits before invalidation.
        self.cache.pop(branch, None)


def compare_reads(store, branch, repeats=101):
    """Time equal work at the Python service boundary, with an already warm cache."""
    dashboard = Dashboard(store)
    expected = dashboard.open_count(branch)  # Exclude the cold miss from this comparison.
    samples = {"direct": [], "warm": []}
    starting_reads = store.reads
    methods = [("direct", store.count_open), ("warm", dashboard.open_count)]
    for trial in range(repeats):
        for name, read in (methods if trial % 2 == 0 else reversed(methods)):
            start = perf_counter_ns()
            value = read(branch)
            elapsed = perf_counter_ns() - start
            assert value == expected
            samples[name].append(elapsed)
    return {
        "reads_per_path": repeats,
        "source_queries_during_pairs": store.reads - starting_reads,
        "direct_median_us": median(samples["direct"]) / 1000,
        "warm_median_us": median(samples["warm"]) / 1000,
    }


def demo():
    db = sqlite3.connect(":memory:")
    try:
        db.execute("CREATE TABLE tickets (branch TEXT, status TEXT)")
        with db:
            db.executemany("INSERT INTO tickets VALUES (?, ?)", (
                ("north" if i % 2 == 0 else "south", "open" if i % 3 == 0 else "closed")
                for i in range(60_000)
            ))
        store = TicketStore(db)
        # Advance only the freshness clock. Benchmark timings use the real clock.
        now = 0
        service = Dashboard(store, ttl=30, clock=lambda: now)
        trace = []

        def record(event):
            count = service.open_count("north")
            trace.append({"event": event, "time_s": now, "count": count, "queries": store.reads})

        record("first read")
        now = 1
        record("repeat read")
        now = 10
        store.add_open("north")  # Another writer bypasses this service.
        record("after external write")
        now = 30
        record("at expiry")
        now = 31
        service.add_open("north")
        record("after service write")
        assert [(r["count"], r["queries"]) for r in trace] == [
            (10000, 1), (10000, 1), (10000, 1), (10001, 2), (10002, 3)]
        return {"fixture_rows_initial": 60000, "trace": trace,
                "timing": compare_reads(store, "north")}
    finally:
        db.close()


if __name__ == "__main__":
    print(json.dumps(demo(), indent=2))

Link copied!

Comments

Add Your Comment

Comment Added!