Skip to content

refactor: generic rwmutex cache for ip and txt#34

Open
lidel wants to merge 2 commits into
masterfrom
fix/cache-cleanup-rwmutex
Open

refactor: generic rwmutex cache for ip and txt#34
lidel wants to merge 2 commits into
masterfrom
fix/cache-cleanup-rwmutex

Conversation

@lidel
Copy link
Copy Markdown
Member

@lidel lidel commented Jun 4, 2026

Problem

The resolver caches sit behind a single sync.Mutex, so every lookup, including a read-only cache hit, serializes on it. A plain RWMutex would let reads run in parallel, but the version that did (before #4) deleted expired entries while holding only the read lock, a data race. That race is why #4 fell back to the single mutex, leaving reads serialized.

Fix

  • reads take a read lock, so concurrent cache hits run in parallel
  • expired entries are deleted under the write lock via double-checked locking: get drops the read lock, takes the write lock, and re-checks the entry before deleting, so a concurrent set that refreshed it is not clobbered (rationale in the get comment in resolver.go)
  • one generic cache[V] holds this logic for both the IP and TXT caches

Reads run concurrently again while expired-entry cleanup stays race-free. vyzo's suggestion in #5 to queue expired entries for a separate write-locked cleanup pass is not needed here: get already takes the write lock on the rare expired hit, so it deletes that one entry inline instead of maintaining a cleanup queue. Closes #5.

lidel added 2 commits June 4, 2026 02:12
Separate expired-entry deletion from reads so the ip and txt caches
can share one generic cache[V] guarded by a read-write mutex.

- a read takes the read lock, so cache hits run in parallel
- get deletes an expired entry under the write lock: it drops the
  read lock, takes the write lock, and re-checks the entry first, so
  a value a concurrent set refreshed in the gap is kept
- a zero TTL stores nothing, so a disabled cache stays empty
- tests cover expiry, the zero-TTL no-op, and concurrent access

closes #5
@lidel lidel requested review from MarcoPolo and sukunrt June 4, 2026 01:45
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.

Optimizing cache cleanup

1 participant