Skip to content
James Ross
articlePublished Updated 7 min read

Multi tenant architecture for a shared SERP cache, without leaking data

By James Ross

In a multi tenant architecture, a shared SERP cache stores one fetched search-results page per keyword, location, language, device and UTC day, then lets every tenant that needs that same page reuse it. A rank-tracking SaaS runs one because a rank check is an expensive upstream fetch with a result that does not depend on who asked. Isolation comes from what the row contains and how reads are scoped, not from giving each tenant a private copy.

A shared cache vault of result page cards read by separate tenant lanes through one-way windows, showing multi tenant architecture.

This is the caching layer of a multi tenant architecture, underneath the hold/charge credit ledger: the ledger decides who pays for a check, and the cache decides whether that check costs anything upstream.

What does a multi-tenant SERP cache actually store?

It stores a purchased search-results page, trimmed to the parts a rank tracker needs: the organic items with their positions and URLs, and the SERP features that appeared alongside them. It does not store a rendered report, a user’s keyword list, or anything that identifies the tenant who triggered the fetch.

That distinction is the design. The expensive object is the same for everyone: the top 100 organic results for “emergency plumber” in one location, on one device, on one day. The provider fetches it as an anonymous query and charges per task, not per reader. Paying for the same page twice because two agencies track the same client keyword would be waste, not isolation.

The row also carries operational fields: the provider’s task id, a status, the measured cost, a fetch timestamp, and the serialised items. Those fields exist for settlement, margin reporting and debugging. None of them is returned by the public API.

Designing the cache key

A cache key has to include every input that can change the response. Get that wrong and the cache does not fail loudly; it returns a plausible result for the wrong query, which is worse.

Key part Why it belongs
phrase_normalised “Emergency Plumber” and “emergency plumber” are the same search; normalising avoids two paid fetches for one phrase
locationCode A SERP for a city is not the SERP for a country; the provider keys locations by code
languageCode The same phrase in a different language returns a different result set
device Desktop and mobile rankings differ, and the product charges them separately
date The UTC day bounds reuse; a result fetched yesterday is not today’s ranking

The date is the UTC day, not a rolling 24-hour window. A rolling window sounds more precise, but it makes the cache key depend on the clock at read time, so two requests seconds apart can disagree about whether a row is fresh. A day boundary is coarse, predictable, and easy to explain: everything fetched today is reusable today, and the first check after midnight is a new fetch.

The normalised phrase is stored alongside the display phrase. Normalisation is the part teams get wrong: lowercasing and collapsing whitespace makes two typed versions of one phrase compare equal, but stemming or reordering words does not belong here, because “plumber emergency” is a different query from “emergency plumber” even when it means the same thing. Normalisation is for de-duplicating typing, not for guessing intent.

Why the unique constraint is the real lock

The uniqueness rule is enforced by a database constraint, not by an application check. Two workers that post the same keyword at the same moment will both try to insert the key; one succeeds, the other gets a duplicate-key error and reads the winner’s row. That is the same pattern as an idempotency key, applied to a cache.

PostgreSQL’s default behaviour matters here: a unique index treats nulls as distinct, so a nullable column in the key would silently allow duplicates. Every key column is therefore non-null. A freshKey column was added later for private fetches; it is what keeps a paid fresh result out of the shared row.

Why tenant isolation is not a cache-key problem

The intuitive fix is to add accountId to the cache key. That would make every tenant’s fetch private, which defeats the point: two agencies tracking the same client keyword would each pay for the same page. The cache is shared on purpose.

Isolation lives one level up, in the run. A tenant’s run has run items, and each run item points at a cache row by id. The query that builds a report starts from the run, which is already scoped to the account, and joins outward. There is no endpoint that accepts a cache id and returns a row.

Three rules make that hold:

  1. Every tenant query goes through a scoped client. A helper wraps Prisma with the account filter so a forgotten where is a type-level omission rather than a data leak. The build plan requires a test proving one tenant cannot read another’s data.
  2. Restricted keys return 404, not 403. A key limited to specific projects returns “not found” for any other project, so project ids cannot be probed by status code.
  3. The cache row never holds tenant data. No account id, no keyword id, no tags, no competitor list. The only shared thing is the SERP.

The failure mode this design accepts is a bug in the join: a report query that starts from the cache table instead of the run table would expose another tenant’s ranking data. That is why the test is a data test, not a schema review. The schema cannot prove isolation; the query path can.

What must never be shared

  • Fresh fetches. A fresh: true request posts a new task with a private key. It is never reused by another account, because the caller paid for a result newer than the shared one.
  • Test-mode data. Keys beginning ts_test_ read a synthetic demo project and never call the provider, so test traffic cannot warm or poison the shared cache.
  • Provider internals. Task ids, raw costs and error bodies stay server-side. A customer sees a rank, a URL, the SERP features and a cached flag.

The cost model in principle

The saving is easy to state and hard to fake: if ten tenants track the same keyword in the same location, on the same device, on the same day, the provider is called once and ten checks are served. The saving is the share of checks that hit the cache, which is why the admin console tracks “dedupe savings” as shared fetches divided by total fetches.

Two rules keep the saving honest:

  • The customer still pays one credit. The product sells a check, not a network call. A cache hit completes immediately and returns cached: true, which is a better experience than a fifteen-minute wait, but it is not free.
  • The cost is attributed, not ignored. For margin reporting, a shared fetch’s measured cost is split evenly across the run items and lookups that used it, with the full-cost figure shown alongside. Without that split, every shared fetch would look like pure profit and every fresh fetch like a loss.

This is also why a “cache hit ratio” is a bad headline metric on its own. A high ratio usually means agencies are tracking overlapping keywords, which is the product working. A high ratio with unexplained upstream spend usually means the key is missing an input and the cache is returning the wrong page.

Comparison: three ways to isolate a shared cache

Approach Upstream cost Isolation mechanism Main risk
Per-tenant cache Highest: one fetch per tenant per day Physical separation Paying repeatedly for identical data
Shared cache, scoped joins Least Application query layer plus tests One unscoped query leaks data
Shared cache with row-level security Low Database policy on every query Policy complexity and connection-pool overhead

Which should you choose?

Use a per-tenant cache when the cached object contains tenant-specific data, such as a rendered report or a saved search. Use a shared cache with scoped joins when the object is a public fact that many tenants need, which is the rank-tracking case. Row-level security is a reasonable third option when several services share one database and you cannot guarantee every service uses the scoped client; it moves the guarantee into the database at the cost of more policies to test.

What broke and what we changed

A test cleanup deleted the shared cache. The engine tests called deleteMany() with no filter on the cache table. That wiped local development data, broke parallel test files, and would have been far worse against a shared environment. The fix was to delete only the fetches the test itself created, resolved through its own run items, after those run items were gone. A shared table changes the meaning of “clean up after yourself”: you cannot truncate a table that other tests depend on.

Mock task ids collided across processes. The task id column is unique, so two parallel test processes could generate the same mock id and one would fail on the constraint. The fix was a per-instance prefix. The same class of bug appears in production when a retry reuses an id: uniqueness on the provider’s identifier is what stops two rows claiming the same task.

The retention rule changed under the feature roadmap. The plan trimmed stored SERP items after 90 days to keep the table small. Then SERP history shipped: a report tab that compares the top 100 results between two dates. That feature reads the stored items, so the housekeeping job was changed to retain them. The lesson is not “keep everything”; it is that a retention rule is a product decision, and trimming a cache is different from trimming a system of record.

Frequently asked questions

Is a shared cache a data leak between customers?

No, if the cached object contains no customer data. The cache row holds a public search-results page keyed by phrase, location, language, device and day. Tenants are isolated at the run level: a report query starts from the tenant's own run and joins outward, and there is no endpoint that accepts a cache id. The risk is an unscoped query, which is why the isolation test targets queries rather than schemas.

Why is the cache keyed by UTC day instead of a rolling window?

A rolling window makes freshness depend on the clock at read time, so two requests seconds apart can disagree about whether a row is reusable. A UTC day boundary is coarse and predictable: everything fetched today is shared today, and the first check after midnight is a new fetch. It also matches how customers think about a daily rank.

Do customers pay for a cached check?

Yes. The product sells a rank check, not an upstream API call, so a cache hit costs one credit and returns cached: true. The customer gets an immediate result instead of a wait of ten to twenty minutes, and the vendor avoids a second upstream charge. The flag exists so the behaviour is visible rather than surprising.

What does a fresh request change?

It adds a private key to the fetch, which forces a new upstream task and prevents the row from being shared with or reused by any other account. It is the only way to get a result newer than one already fetched that day. It costs the same credit but takes the normal queue time.

Should the cache key include the tenant id?

Only if the cached response can differ by tenant. A public SERP does not, so adding the tenant id would multiply upstream cost for no isolation benefit. If the cached object is personalised, such as a report layout or a filtered dataset, it is not a shared cache and should be keyed per tenant.

How do you prove one tenant cannot read another's data?

With a test that creates two accounts, writes a row in each, and then tries to read the second account's row through every query path that accepts an id. The assertion is that the read returns nothing or a 404, not that the page renders. A schema review cannot prove this, because the leak would be in a query, not in a column.