Navigation
  • Home
  • Work
  • About
  • Writing
  • Contact
Socials
LinkedInGitHubEmailResume
Writing
Code by AsjadAsjad Anwar
  • Home
  • Work
  • About
  • Writing
  • Contact
17 October 2026 · 6 min read

Caching a third-party API and clearing it with a webhook

Per Diem is a mobile-first menu for a multi-location café, which I built on my own in a day. The menu lives in Square. The browser cannot call Square directly, because the access token has to stay on a server, and building one menu response takes several Square calls: a paginated item search plus a category list. Doing that on every page view is slow and wasteful, but a cached menu that shows an old price is worse.

The answer I used has two parts. An Express proxy caches each transformed response in memory with a time-to-live (TTL, the number of seconds an entry is kept) of 300 seconds. Square then calls a webhook, an HTTP request it sends to my server when something changes, and that request deletes the cached menu entries once its HMAC-SHA256 signature has been verified. The TTL is the safety net, and the webhook is what keeps the menu fresh.

Why a menu app needs a proxy in front of Square

The proxy exposes three read endpoints: GET /api/locations, GET /api/catalog?location_id=... and GET /api/catalog/categories?location_id=.... Each returns a small shape the front end can render directly, with items already filtered to one location and grouped by category.

Getting there is not one call. The catalogue service pages through Square's catalogue search 100 items at a time, with a hard stop at 50 pages, then lists every category separately to resolve names. That second call was added in the repository's second commit, after I found that the related objects in the search response did not reliably include categories. All of that work is the same for every visitor at the same location, which makes it a good thing to cache.

Cache-aside with a TTL in an Express service

Cache-aside means the service checks the cache, fetches from the source on a miss, stores the result and returns it. Every service function has the same outline:

const cache = getCache();
const cacheKey = CacheKeys.catalog(locationId, categoryId);

const cached = await cache.get<CatalogResponse>(cacheKey);
if (cached) {
  logger.info("Cache hit: catalog", { locationId, categoryId });
  return cached;
}
// ...fetch from Square, filter, group...
await cache.set(cacheKey, result);

What gets cached is the finished response, not Square's raw objects, so a hit skips the transformation as well as the network.

There are two TTLs, both read from environment variables and validated at startup as positive integers. Catalogue and category entries default to 300 seconds. Locations default to 3,600 seconds and pass that TTL explicitly on set, because a café opens a new branch far less often than it changes a price.

If Square fails, the service throws a 502 with a generic message and nothing is written, so an error is never cached.

Cache keys designed for invalidation

Keys are built in one file, from three prefixes: sq:locations, sq:catalog and sq:categories. A catalogue key is sq:catalog:<locationId>, or sq:catalog:<locationId>:<categoryId> when a category filter is applied. The same file exports the patterns sq:catalog:* and sq:categories:*.

Putting the prefix first is what makes "delete everything about the menu" a single pattern delete. The cache sits behind a five-method interface (get, set, del, delByPattern, flush) with two implementations, chosen by one environment variable. The default wraps node-cache and turns the glob into a regular expression:

async delByPattern(pattern: string): Promise<void> {
  const allKeys = this.cache.keys();
  const regexPattern = pattern
    .replace(/[.+?^${}()|[\]\\]/g, "\\$&")
    .replace(/\*/g, ".*");
  const regex = new RegExp(`^${regexPattern}$`);
  const matchingKeys = allKeys.filter((key) => regex.test(key));
  if (matchingKeys.length > 0) {
    this.cache.del(matchingKeys);
  }
}

The Redis implementation does the same job with SCAN in batches of 100 followed by one DEL, so it never issues a blocking KEYS command.

Verifying a Square webhook signature in Express

An endpoint that clears a cache is an endpoint anyone can hit, so it has to prove the caller is Square. Square signs each webhook, and the validator recomputes that signature: an HMAC-SHA256 (a keyed hash) over the notification URL followed by the raw request body, using the signature key as the secret, encoded as Base64. The request carries its copy in the x-square-hmacsha256-signature header.

const payload = notificationUrl + body;
const expectedSignature = crypto
  .createHmac("sha256", signatureKey)
  .update(payload, "utf8")
  .digest("base64");

const expectedBuffer = Buffer.from(expectedSignature, "base64");
const receivedBuffer = Buffer.from(signature, "base64");
if (expectedBuffer.length !== receivedBuffer.length) return false;
return crypto.timingSafeEqual(expectedBuffer, receivedBuffer);

timingSafeEqual compares in constant time, so the response time does not leak how many bytes matched. It throws on buffers of different lengths, hence the length check first.

The detail that is easy to get wrong is "raw request body". If express.json() parses the body first, the exact bytes Square signed are gone, and re-serialising the object is not guaranteed to reproduce them. So the webhook path gets a raw parser, registered before the global JSON parser:

app.use("/api/webhooks", express.raw({ type: "application/json", limit: "10mb" }));
app.use(express.json({ limit: "10mb" }));

In the handler req.body is a Buffer. It is verified first, and only then parsed with JSON.parse. A bad signature returns 401, and a body that passes verification but is not valid JSON returns 400. The other API routes can require an x-api-key header, and the webhook path is exempted from that check, because Square cannot send it. The signature is its authentication.

Clearing the cache when the catalogue changes

After verification the handler answers before it does any work:

res.status(200).json({ received: true });

processWebhookEvent(event).catch((err: Error) => {
  logger.error("Error processing webhook event", {
    error: err.message,
    eventType: event.type,
  });
});

The service acts on one event type, catalog.version.updated. It runs the two pattern deletes in parallel and logs the result. Any other event type is logged and ignored.

Invalidation is deliberately coarse. The handler does not try to work out which item changed or which location it belongs to. It drops every catalogue and category entry, and the next request for each location rebuilds its own. A failed delete is logged and swallowed, since the 200 has already gone out. In that case the TTL takes over and the entry is gone within 300 seconds anyway.

Trade-offs I would change next

Reading the code again, these are the things I would change.

  • No protection against a stampede. Two requests that miss at the same moment both call Square. Right after a webhook clears everything, that is exactly when it happens.
  • A category filter costs a full fetch. A filtered request has its own key, and on a miss it downloads the whole catalogue again and filters in memory. Filtering the already cached location entry would avoid that.
  • The browser has its own cache. The front end keeps catalogue queries fresh for five minutes, and the webhook cannot reach it. Server-side invalidation only helps the next person who actually asks the server.
  • Locations are not invalidated. The webhook leaves sq:locations alone, so a new branch can take up to an hour to appear.
  • The memory cache is per process. A webhook clears only the instance that receives it. The Redis adapter exists for that case, but it is opt-in.

Takeaways

  • Cache the transformed response behind your own proxy, and keep the third-party token on the server.
  • Give every cache entry a TTL even when a webhook invalidates it, because the webhook can fail or never arrive.
  • Put the resource prefix first in cache keys so a whole family can be deleted with one pattern.
  • Verify webhook signatures against the raw bytes, which in Express means registering express.raw() on that path before express.json().
  • Acknowledge the webhook first and invalidate afterwards, and prefer clearing too much over working out exactly what changed.
Node.jsExpressCachingWebhooks

From the project: Per Diem

Keep reading

  • 30 September 2026 · 6 min read

    React Testing: Unit, Integration and End-to-End in One App

    How I split 46 Vitest tests and 17 Playwright tests across unit, integration and end-to-end levels in a small React app, with an axe-core accessibility check.

  • 28 November 2026 · 7 min read

    RTK Query caching for sensitive data: what never to cache

    How I set up RTK Query caching in a React admin console that shows patient data: memory only, 30-second revalidation, and reads that are never repeated.

All writing

Let’s work
together

Get in touch
theasjadanwar@gmail.com+92 321 4010734Resume (PDF)LinkedInGitHub
Based inLahore, Pakistan (UTC+5)
SocialsLinkedInGitHub