All posts

Shaping a URL shortener on Cloudflare Workers for durability

By Andrea Bruno9 min read

A link shortener looks simple: look up a word, redirect the visitor. The work is around that lookup. The redirect has to be fast everywhere, counting the click must not slow it down, and a link printed on a poster has to mean the same thing years later.

rdyrct does all of it on one Cloudflare Worker. This post follows one link from save to chart, with the code at each step, including two parts I rebuilt after they broke in production. It assumes you know what a Worker is. The code is shortened from the open source repository.

One Worker for every host

Every request reaches the same Worker, which routes on the host name first. rdyrct.com serves the app and the API, rdyr.cc only redirects, and any other host is a customer's own domain.

One Worker behind every host Three hosts, rdyrct.com for the app and API, rdyr.cc for shared short links, and a customer's domain such as go.yourbrand.com, all send requests to one Worker. The Worker uses six Cloudflare services: KV maps slugs to destinations, D1 is the source of truth, R2 holds QR code logos, a Durable Object buffers clicks, Workflows run jobs that wait, and a Queue retries KV and R2 writes. rdyrct.com the app and API rdyr.cc shared short links go.yourbrand.com a customer's domain One Worker picks a route by host, then by path KV slug to destination D1 the source of truth R2 QR code logos Durable Object the click buffer Workflows jobs that wait Queue KV and R2 retries
Figure 1One Worker behind every host

Each Cloudflare service arrives as a typed binding on env, with no connection strings or client libraries, and one deploy ships everything.

Random slugs, issued once

A new link on rdyr.cc gets a random seven-character slug. The alphabet leaves out 0, o, 1, l and i, so nobody misreads one off a poster, and still allows about 27 billion slugs.

A slug is never issued twice, even after its link is deleted. Old posts and printed QR codes still point at it, and a reused slug would send their readers to a stranger's page. (The exception is a link made on the home page without an account. If nobody claims it within 24 hours, its slug goes back in the pool.) Every slug goes into a table, and its primary key does the check:

for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
  const slug = draw();
  const issued = await db
    .insert(schema.issuedSlugs)
    .values({ slug, issuedAt: Date.now() })
    .onConflictDoNothing()
    .returning({ slug: schema.issuedSlugs.slug });
  if (issued.length > 0) return slug;
}
Every shared slug is issued once The Worker draws 52t8q3s, which is already in issued_slugs, so the insert does nothing and the draw is thrown away. It draws p4hw7nc, the insert adds a row, and that slug is issued for good. random draw x7mq2ab 94tkcz8 52t8q3s m3vd8qe t6hw2kp p4hw7nc ON CONFLICT DO NOTHING issued_slugs every slug ever issued r8bq4zm link deleted 52t8q3s live taken, draw again x9fd2ka live hq3v8tm link deleted p4hw7nc issued just now
Figure 2Every shared slug is issued once

There is no read before the insert, so two saves cannot race between a check and a write. If no row comes back, the slug was taken and the loop draws again.

Why not a counter

A base62 counter never repeats and needs no check, which is why system-design guides suggest it. But anyone can walk a counter (if rdyr.cc/4c exists, so do 4b and 4d) and read the number of links off the latest code. Shuffling the counter hides the order, but Sqids, a common tool for it, warns that anyone who works out the alphabet can decode its codes and learn the count. (1)

Random slugs can still be guessed. In 2016, researchers at Cornell Tech brute-forced the 5- and 6-character links of two big shorteners and found private OneDrive files and directions to people's homes. (2) With a million links on rdyr.cc, one guess in 27,500 would hit one. A rate limit slows a scanner down, but a link that guards something private should not rely on its slug staying secret.

D1 first, then KV, then the response

D1, Cloudflare's SQLite database, holds the truth. KV is a copy for fast reads. A save commits the row to D1, writes the KV key, and only then responds.

When a new link starts working Before the fix, the save returned at once but KV was written 5.7 seconds later, so a click at 4 seconds got a 404, and that 404 stayed cached until 58 seconds. After the fix, the save writes D1 and then KV before it returns, and clicks at 1 and 4 seconds get a 302. Before the fix After the fix 0 s 2 s 4 s 6 s 8 s save returns 404 404 cached until 58 s KV written save: D1, then KV, then return 302 302
Figure 3When a new link starts working

Until October the KV write went through a queue that waited up to five seconds to fill a batch. A click in that gap got a 404, and KV cached the 404 for up to a minute. Measured in production:

First click after creating the linkBefore the fixAfter the fix
4 seconds404, and still 404 until 58 seconds302
8 seconds, nobody clicked earlier302302

The fix writes KV inside the request, keeps the queue only for writes that fail, and has the redirect ask D1 on a miss (shown below). (3)

Retries that carry only a key

A failed KV write leaves a queue message that names the key and carries no value:

export type StorageMessage =
  | { op: "kv_sync"; key: string }
  | { op: "r2_delete"; key: string }
  | { op: "org_sync"; orgId: string };

The retry reads D1 when it runs and copies what is true then. A message that carried the value could run after a later edit and undo it.

Following a link

KV is copied to Cloudflare's data centers, so a read is answered near the visitor. A shared link costs one read (slug:k7m2xqp). A custom domain costs two, because the Worker first reads domain:go.yourbrand.com to find who owns the host.

Measured from Milan on 4 December 2026, 40 redirects on one open connection came back in a median of 38 ms, and 55 ms at the 90th percentile. About 16 ms of that is the network round trip. The first requests on new connections were slower, a few of them up to half a second.

What happens when someone clicks a short link The visitor asks the Worker for /k7m2xqp. The Worker reads the key slug:k7m2xqp from KV and gets back the destination and link id. The Worker answers the visitor with a 302 redirect. Only after the response is sent does the Worker hand the click to the click buffer. Visitor Worker KV Click buffer GET /k7m2xqp slug:k7m2xqp { url, linkId } 302 Location After the response is sent add(click)
Figure 4What happens when someone clicks a short link

Counting the click after the response

waitUntil sends the response and keeps the Worker running until the promise it was handed settles, so the visitor never waits for analytics:

function redirectWithClick(c: Context<AppEnv>, hit: KVLink): Response {
  c.executionCtx.waitUntil(enqueueClick(c, hit));
  return c.redirect(hit.url, 302);
}

enqueueClick catches its own errors. If counting fails, the redirect has still worked.

On a KV miss, asking D1

A KV write can take a minute or more to reach every data center, and a miss can be cached for about as long. (4) So on a miss, the Worker asks D1 before it answers 404.

const hit = await resolveSlug(c.env, slug, hostname); // KV
if (hit || !SLUG_RE.test(slug)) return hit;
return await desiredLink(db, slug, hostname);         // D1, only on a miss

The regular expression keeps bots that probe paths like /wp-login.php away from the database.

Counting clicks

A queue that hit its limit

The first version queued every click for a consumer to write to D1. On 10 September 2026, a free account started using rdyrct for SMS phishing. Its two links took 3,388 redirects that day, against a normal day of about 35. (5)

Each click cost about three queue operations, and at rdyrct's traffic a batch never filled. At 21:36 UTC rdyrct passed the free plan's 10,000 operations a day, and Cloudflare stopped both queues until midnight. Redirects kept working, but clicks were lost and saves returned errors.

Banning the account ended the incident. The design still spent queue operations in step with clicks, so I replaced the queue (6) with a Durable Object, a class that Cloudflare runs as a single instance, which holds clicks in memory.

A Durable Object that batches clicks

The click buffer Clicks from every redirect go into the click buffer, a Durable Object that holds them in memory. Every ten seconds it writes them to D1 as one transaction, which updates four tables: clicks, click_hourly, click_daily and click_daily_dims. clicks from every redirect Click buffer a Durable Object, held in memory one write every 10 seconds D1 one transaction clicks click_hourly click_daily click_daily_dims
Figure 5The click buffer

The first click in an empty buffer sets an alarm ten seconds out, and the alarm writes the whole buffer at once. A burst of 5,000 clicks writes straight away.

export class ClickBuffer extends DurableObject<Env> {
  #buf: ClickMessage[] = [];
  #flushMs = Number(this.env.CLICK_FLUSH_MS) || FLUSH_MS;

  async add(row: ClickMessage): Promise<void> {
    this.#buf.push(row);
    if (this.#buf.length >= MAX_BUFFER) {
      await this.#flush();
      return;
    }
    if ((await this.ctx.storage.getAlarm()) === null) {
      await this.ctx.storage.setAlarm(Date.now() + this.#flushMs);
    }
  }

  async alarm(): Promise<void> {
    await this.#flush();
  }
}

The flush swaps the array out before its first await, so a click that arrives mid-write goes into the next batch:

async #flush(): Promise<void> {
  if (this.#flushing || this.#buf.length === 0) return;
  this.#flushing = true;
  const rows = this.#buf;
  this.#buf = [];
  try {
    const { retry, hadFailure } = await insertClicks(this.env, rows);
    // ...

Each batch is one D1 transaction that stores the raw clicks and updates the hourly and daily totals the charts read. Every click carries an id, and the insert skips ids it has already stored, so a flush that runs twice counts nothing twice.

What the buffer trades away

The buffer lives in memory. If Cloudflare restarts the object before its alarm, up to ten seconds of clicks are lost. Storing each click would close that gap and bring back a write per click. For analytics that is a fair trade, and links and domains never go through the buffer. By my estimate at the time, the free plan's ceiling went from about 3,300 clicks a day to about 100,000.

What a click keeps

A stored click has four fields: the country, the referring host (never the full address), the device and the time. The IP address is not one of them.

One stored click A stored click has a country, PT; a referrer host, news.ycombinator.com; a device, mobile; and a time. The IP address is never stored. One click, as stored Country PT Referrer news.ycombinator.com Device Mobile Time 4 Dec 2026, 10:41 IP address 203.0.113.42 never stored
Figure 6One stored click

To stop one visitor flooding a link's numbers, the Worker keys Cloudflare's rate limiter on an HMAC-SHA-256 of the address, made with a server secret. The counter lasts 60 seconds, and the digest is never stored.

Run it yourself

Everything above is in the repository, and bun run deploy puts a copy on your own Cloudflare account. It builds with Vite 8 and Cloudflare's Vite plugin, its tests run on Vitest, and Oxlint checks every change.

Sources

  1. Sqids: what the library is and is not good for. ↩
  2. Georgiev and Shmatikov, Gone in Six Characters: Short URLs Considered Harmful for Cloud Services (2016): scanning short links for private content. ↩
  3. rdyrct pull request #284: a new link redirects on its first click, with the measurements from before the fix. ↩
  4. Cloudflare docs, How KV works: on reads being cached at the edge, misses included. ↩
  5. rdyrct incident report, 10 September 2026: the queue limit, the timeline and the follow-up. ↩
  6. rdyrct issue #225: replacing the click queue with a Durable Object buffer, with the cost estimates. ↩

Keep reading. More from the blog.

  1. rdyrct 1.2: a new app, a setup flow, and email only after a yes

    rdyrct 1.2.0: every screen redesigned, a setup flow to a team's first link, domain and invites, CSV export, opt-in email lists, and safer links.

  2. rdyrct 1.1: bring your links from Bitly, then tag and track them

    rdyrct 1.1.0: import links from Bitly, Short.io, Rebrandly or Dub with the same short URLs, a free UTM builder, homepage links and one-step self-hosting.

  3. How dead bit.ly links got hijacked, and why rdyrct never reuses a slug

    Old brand tweets now preview pages their owners never linked: a dead short link's slug went to someone else. How the attack works, and the rule that stops it.

Short links on your own domain. Free to start.

Links, QR codes and click analytics for your team. No visitor IP address is ever stored.