Skip to content

fix(lock): expire MemoryLocker locks whose request ended on Cloudflare Workers - #2540

Merged
dinwwwh merged 2 commits into
mainfrom
claude/cloudflare-workers-compat-854686
Nov 23, 2026
Merged

dinwwwh merged 2 commits into
mainfrom
claude/cloudflare-workers-compat-854686

Conversation

@dinwwwh

@dinwwwh dinwwwh commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #2534 and #2535. Those fixed the lazy router. This fixes the same problem in MemoryLocker.

Problem

On Cloudflare Workers, a timer dies with the request that started it, and clearTimeout from another request does nothing. MemoryLocker only expired a holder through a setTimeout that the holder itself started. So if the holder's request ended, for example because the client disconnected, the key stayed locked for good. Every later caller then timed out. The same thing happened when a waiter was handed the lock after its own request had already ended.

Fix

Lock expiry is now a deadline on performance.now(), enforced by whichever request is still running:

  • Later callers: a new lock() call takes over a holder whose time has passed.
  • Waiters' own timers: each waiter wakes no later than the earliest time a holder ahead of it could expire. That is the holder's expiresAt, or now + ttl of any waiter still ahead of it. Every check runs from the waiter's own request.
  • Handover: the new holder's ttl starts when it receives the lock, so a holder whose request ended keeps the lock for its ttl at most.
  • Timed-out waiters: at handover, waiters whose timeout has passed are skipped, since their timers may be dead.

The holder's own expiry timer stays as a fallback, so on Node an expired lock is still freed promptly when nobody is waiting. ttl and timeout above 2^31-1, including Infinity, skip or clamp their timers instead of overflowing to 1ms.

Inside a Durable Object all requests share one context, so behaviour there is unchanged.

Notes for reviewers

  • Separate deadline timer per waiter: this is intentional. Node timers can fire about 1ms before performance.now() reaches the target, so the timer, not the clock, decides when a waiter times out. Folding it into the wake timer made timeouts up to about 1ms late. The test times out by its own timer when only setTimeout is faked covers this.
  • How often waiters wake: while a waiter with ttl T is queued ahead, the waiters behind it wake about once every T for as long as the lock is held. That waiter could get the lock at any moment, from another request, and its own request may already have ended. Each wake scans the waiters ahead, which is linear in the waiter's position. With the same ttl for everyone, this is about one wake per ttl. A cached bound from join time would be cheaper but goes stale: a waiter behind a short-ttl waiter that left would keep waking every 1ms. stops waking often once the short-ttl waiters ahead have left covers this.
  • Dead holder with no waiters: on Workers, it stays in the map until the key is locked again. The old code behaved the same.

Testing

  • New tests: they drop setTimeout to simulate a request that has ended. They cover a dead holder, a dead waiter handed the lock, a handover to a shorter ttl, skipping timed-out waiters, a system clock jump, timers past the 2^31-1 limit, and how often waiters wake.
  • Real workerd: a Miniflare harness was run with handle_cross_request_promise_resolution on, the default since 2024-10-14. @cloudflare/vitest-plugin always turns this flag off, so the package's workerd tests can't reproduce the bug. Holders and waiters whose requests end early used to leave the key locked forever. Now the lock is acquired after the ttl.
  • Checks: pnpm check passes. The lock tests pass (46).

…e Workers

On Workers a timer dies with the request that started it, so a holder or
waiter whose request ended left its key locked forever. Lock expiry is now
a deadline on performance.now(), enforced by later callers and by every
waiter's own timers, which wake by the time a waiter ahead could expire.
A handover starts the new holder's ttl, and waiters whose timeout passed
are skipped.
@pkg-pr-new

pkg-pr-new Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
More templates

@orpc/ai-sdk

npm i https://pkg.pr.new/@orpc/ai-sdk@2540

@orpc/arktype

npm i https://pkg.pr.new/@orpc/arktype@2540

@orpc/bun

npm i https://pkg.pr.new/@orpc/bun@2540

@orpc/client

npm i https://pkg.pr.new/@orpc/client@2540

@orpc/cloudflare

npm i https://pkg.pr.new/@orpc/cloudflare@2540

@orpc/contract

npm i https://pkg.pr.new/@orpc/contract@2540

@orpc/effect

npm i https://pkg.pr.new/@orpc/effect@2540

@orpc/evlog

npm i https://pkg.pr.new/@orpc/evlog@2540

@orpc/hibernation

npm i https://pkg.pr.new/@orpc/hibernation@2540

@orpc/json-schema

npm i https://pkg.pr.new/@orpc/json-schema@2540

@orpc/experimental-lock

npm i https://pkg.pr.new/@orpc/experimental-lock@2540

@orpc/mcp

npm i https://pkg.pr.new/@orpc/mcp@2540

@orpc/msw

npm i https://pkg.pr.new/@orpc/msw@2540

@orpc/nest

npm i https://pkg.pr.new/@orpc/nest@2540

@orpc/next

npm i https://pkg.pr.new/@orpc/next@2540

@orpc/node

npm i https://pkg.pr.new/@orpc/node@2540

@orpc/openapi

npm i https://pkg.pr.new/@orpc/openapi@2540

@orpc/experimental-openapi-inference

npm i https://pkg.pr.new/@orpc/experimental-openapi-inference@2540

@orpc/opentelemetry

npm i https://pkg.pr.new/@orpc/opentelemetry@2540

@orpc/pinia-colada

npm i https://pkg.pr.new/@orpc/pinia-colada@2540

@orpc/pino

npm i https://pkg.pr.new/@orpc/pino@2540

@orpc/publisher

npm i https://pkg.pr.new/@orpc/publisher@2540

@orpc/ratelimit

npm i https://pkg.pr.new/@orpc/ratelimit@2540

@orpc/server

npm i https://pkg.pr.new/@orpc/server@2540

@orpc/shared

npm i https://pkg.pr.new/@orpc/shared@2540

@orpc/swr

npm i https://pkg.pr.new/@orpc/swr@2540

@orpc/tanstack-query

npm i https://pkg.pr.new/@orpc/tanstack-query@2540

@orpc/trpc

npm i https://pkg.pr.new/@orpc/trpc@2540

@orpc/valibot

npm i https://pkg.pr.new/@orpc/valibot@2540

@orpc/zod

npm i https://pkg.pr.new/@orpc/zod@2540

commit: 87697cf

@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Bug Fixes
    • Improved in-memory lock handling when locks expire, waiters time out, or system-clock changes affect expiration checks.
    • Reduced unnecessary timer wakeups for long-lived locks and waiters.
    • Improved handling of locks and waiters with very long or infinite time limits, and of expired locks when no waiters are present.
    • Ensured queued waiters with expired time limits are skipped so an eligible waiter can acquire the lock.

MemoryLocker now tracks holder expiration timestamps and waiter deadlines. It checks expiration during acquisition and while waiters are queued, and skips timed-out waiters during handover. Tests cover expiration, timeout, timer suppression, clock changes, and infinite TTL or timeout values.

Changes: Memory lock timing

Layer / File(s) Summary
Holder expiration and acquisition
packages/lock/src/adapters/memory.ts, packages/lock/src/adapters/memory.test.ts
MemoryLocker stores holder expiration timestamps and releases expired entries during acquisition. Tests cover acquisition after expiration, forward system-clock changes, and removal of expired entries without waiters.
Waiter deadlines and handover
packages/lock/src/adapters/memory.ts, packages/lock/src/adapters/memory.test.ts
Waiters track TTLs and deadlines. MemoryLocker schedules bounded expiry checks, rejects timed-out waiters, and hands the lock to the first unexpired waiter. Tests cover timeout handling, suppressed timers, handover, and infinite TTL or timeout.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Merge Risk: Minimal · up to 87697

This change makes in-memory locks recover after a holder's or waiter's timer stops, as on Cloudflare Workers. No outstanding merge-blocking concern was found, and the added tests cover the main new paths.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the change: MemoryLocker locks whose request ended on Cloudflare Workers now expire. The raw summary and objectives describe the same change: lock expiry is enforced by a performance.n…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description states the problem (MemoryLocker locks stuck on Cloudflare Workers when a holder's or waiter's request ends and its timer stops), the fix (performance.now() deadlines, waiter wake-up s…
Full details: Title check

Explanation

The title names the change: MemoryLocker locks whose request ended on Cloudflare Workers now expire. The raw summary and objectives describe the same change: lock expiry is enforced by a performance.now() deadline, and holders and waiters whose requests ended no longer keep the key locked. The title is specific and matches the primary change.

Full details: Description check

Explanation

The description states the problem (MemoryLocker locks stuck on Cloudflare Workers when a holder's or waiter's request ends and its timer stops), the fix (performance.now() deadlines, waiter wake-up scheduling, handover TTL reset, skipping timed-out waiters, timer limits), reviewer notes, and testing. It matches the changeset in packages/lock/src/adapters/memory.ts and memory.test.ts, so it is related and specific enough to pass.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 89f7896e-00be-4356-8bb4-ef1160938318
Commits

Reviewing files that changed from the base of the PR and between 8583f1d and 87697cf.

Files selected for processing: 1

  • packages/lock/src/adapters/memory.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.

@codecov

codecov Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 5 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 40 untouched benchmarks
⏩ 2 skipped benchmarks1


Comparing claude/cloudflare-workers-compat-854686 (87697cf) with main (e067300)

Open in CodSpeed

Footnotes

  1. 2 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Preview URL Updated (UTC)
✅ Deployment successful!
View logs
orpc 87697cf Commit Preview URL

Branch Preview URL
Nov 23 2026, 09:37 AM

@dinwwwh
dinwwwh requested a balanced review from Copilot November 23, 2026 09:40

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test payload sanity check.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

wakeAt = Math.min(wakeAt, now + ahead.ttl)
}

timer = setTimeout(check, Math.min(MAX_TIMEOUT_DELAY, Math.max(1, wakeAt - now)))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

short body

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ Minor suggestions only. One unbounded wake loop worth a look; otherwise this is a solid fix.

(Heads-up: an earlier submission of mine — "Test payload sanity check." with a short body comment — was a malformed tooling payload, not a review. This one supersedes it.)

Approach: sound — expiry becomes a performance.now() deadline that whichever request is still alive enforces, instead of depending on a timer the holder started. Same shape of fix as #2535, and it does resolve the "locked for good" failure on Workers, including the waiter-handover case.

Reviewed changes

  • Deadline-based entry — MemoryLockEntry.expiresAt replaces the stored timer handle, and lock() starts with releaseExpired(), so any later caller reclaims a holder whose deadline passed (also deleting an expired entry nobody waits for).
  • Waiter wake chain — wait() records ttl/deadline, keeps a separate deadlineTimer so timeouts are not late on Node's early-firing timers, and arms a wake timer at min(deadline, entry.expiresAt, now + ttl of each waiter ahead).
  • Handover — release() skips waiters whose deadline passed, installs the next live one with expiresAt = now + next.ttl, and drops the entry when nobody took the lock.
  • Timer overflow — MAX_TIMEOUT_DELAY makes ttl/timeout of Infinity or above 2^31-1 skip their timers instead of overflowing to 1ms.
  • Tests — 13 new cases, incl. a withoutTimers() helper that stubs globalThis.setTimeout to stand in for an ended request, plus the two follow-ups covering a handover where every waiter had already timed out and a settled waiter whose clearTimeout never lands.

I ran packages/lock (48 passed, 18 skipped) plus a scratch fuzz harness mixing never-settling holders with 200 live callers on one key: mutual exclusion held (maxActive === 1), every live caller completed with timeout: Infinity, and entries drained to 0. A waiter's captured entry can never diverge from the map's entry while it is live, because an entry leaves the map only once all of its waiters are settled.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

Comment thread packages/lock/src/adapters/memory.ts Resolved
@dinwwwh
dinwwwh merged commit ab8311a into main Nov 23, 2026
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants