Course lesson 17 · Smart Routing Service

Speed things up with KV

One study unit · Read, recall, then practice · Original video 00:12:06

The redirect service adds a KV cache to reduce repeated database round trips, especially for visitors far from the demonstrated D1 location. It first looks up the link ID in KV, validates cached JSON, and falls back to D1 on a miss or invalid cached value. A successful database lookup populates KV with a 24-hour expiration before returning the same link shape used by the routing helper.

Primary source: course video 17 · Supplied English subtitles · 00:12:06.

Understand the idea

What the course does

  1. Create a stage KV namespace, bind it as cache in the data service, and regenerate environment types.
  2. Build a helper that reads one ID from KV and returns either a validated link object or no usable cached result.
  3. Build a coordinator that falls back to the shared D1 query and returns not found if neither source yields a link.
  4. Serialize successful database results into KV with the demonstrated 24-hour expiration.
  5. Replace the direct database call in the route with this cache-aware helper.
  6. Deploy, compare first and repeated redirects, and optionally add cache-hit logs to inspect through the Worker dashboard.

Watch for

Recall before revealing

After editing a link in D1, why might the redirect still use its previous destination?

Reveal the explanation

The routing service can continue using a cached copy until it is invalidated, replaced, or expires; KV visibility is also eventually consistent.

Try it

Diagram the cache hit, cache miss with a database record, and missing-link paths, then inspect logging for one repeated link request.

Check your result

You can explain which paths call D1, when KV is populated, and why freshness needs an explicit policy.

Practice prompts and answer checks are added teaching material. Answer from memory first, then compare and explain any difference.

Rewatch only what you need

Open this lesson in your original course library and seek to the times below. Videos are not hosted on this site.

Companion primary documentation: How Workers KV works. For recorded API names, commands, limits, and prices, check the version you use.

← Previous   Next →