We are going to design a bounded-staleness cache that uses stamps (like logical timestamps or version numbers) and TTLs (time-to-live) to ensure that cached data is not too stale. Additionally, we want to ensure fairness so that no request starves.
Key features:
Bounded staleness: We want to limit how stale a cached value can be. We can use a combination of TTL and stamps (or versions) to achieve this.
Stamps: Each update to the cache comes with a stamp (which could be a sequence number, a timestamp, or a version). We can use this to check if the cached value is too old compared to the current stamp.
TTL: Even if we don't have a newer stamp, we don't want to keep data forever. We set a time limit.
Fairness: We want to avoid starvation of requests, especially when the cache is under heavy load or when we are waiting for a refresh.
Design considerations:
We'll have a cache that stores:
value: the cached data
stamp: the stamp (version) of the cached data
expiry: the absolute time when this cache entry expires (based on TTL)
We also need:
A way to get the current stamp (from the data source) and the current time.
A mechanism to refresh the cache when it's stale or about to expire.
Bounded staleness can be defined in two ways:
a) By time: We don't want data older than X seconds (TTL).
b) By stamp: We don't want data with a stamp older than the current stamp by more than N versions (or we want the stamp to be at least the current stamp minus a threshold).
But note: stamps are usually increasing. So we can define a maximum allowed stamp gap.
However, note that if we use both TTL and stamp, we can have two conditions for staleness:
Condition 1: The cache entry's stamp is too old (say, current_stamp - cached_stamp > max_stamp_gap)
Condition 2: The cache entry's expiry time has passed.
We can combine by: an entry is valid if (current_time < expiry) AND (current_stamp - cached_stamp <= max_stamp_gap)
But note: the current_stamp is the stamp of the latest update in the data source. We need to know the current stamp. How do we get it?
We can have a background process that updates the current stamp and time, but note that the current stamp is only updated when there's an update in the data source.
Alternatively, we can think of the cache as having two dimensions of staleness: time and version.
But in practice, we might not have a way to get the current stamp without querying the data source. So we have to be cautious.
Another approach: when we update the cache, we record the stamp and the time. When we read, we check:
If the cache is missing, we fetch (and update the cache).
If the cache is present, we check:
if (current_time - cache_fetch_time > TTL) OR (current_stamp - cache_stamp > max_stamp_gap) then we need to refresh.
But again, we need to know the current_stamp. And we don't want to fetch the current stamp on every read because that might be expensive.
We can have a separate process that periodically updates the current stamp? But that might not be real-time.
Alternatively, we can design the cache to be updated by the data source (push) when there's a change, but that might not be feasible in all scenarios.
Let's think about a pull-based cache that checks staleness by both TTL and stamp.
We assume that the data source provides:
The current value and current stamp (when we query).
We can also get the current time from the system.
We want to avoid thundering herd problem when the cache expires.
We can use a technique similar to "stale-while-revalidate" but with bounded staleness.
We can have:
On a read request:
1. If cache is missing, we fetch from the data source (blocking the request) and update the cache.
2. If cache is present, we check if it's still fresh by:
fresh = (current_time < cache.expiry) and (current_stamp - cache.stamp <= max_stamp_gap)
But wait: we don't have current_stamp without querying the data source?
We have a problem: to check the stamp condition, we need the current stamp from the data source. But we don't want to query the data source on every read.
Idea: We can have a background process that periodically updates the current stamp (and maybe time) from the data source. But then the current stamp might be stale.
Alternatively, we can relax the stamp condition: we can only check the stamp when we update the cache (i.e., when we fetch). So:
We set two thresholds:
TTL: absolute time (say 10 seconds)
max_stamp_gap: (say 5 versions)
When we fetch from the data source, we get:
value, stamp, and we note the fetch time.
We cache:
value, stamp, expiry = fetch_time + TTL, and also record the stamp at the time of fetch.
Then on a read, we check:
if (current_time < cache.expiry) then we can use the cache without checking the stamp?
But note: the stamp condition might be violated even if the TTL hasn't expired?
Actually, if we want bounded staleness by stamp, we must check the stamp. But we don't want to get the current stamp on every read.
So we can do:
code
We have two ways the cache becomes stale:
1. Time: if current_time >= cache.expiry, then we need to refresh.
2. Stamp: if the current stamp (which we don't have) is more than max_stamp_gap ahead of cache.stamp.
How to handle stamp without querying?
We can have a separate cache for the current stamp? Or we can have a background job that updates the current stamp and stores it in a variable. Then we can check:
code
if (current_time < cache.expiry) and (current_stamp - cache.stamp <= max_stamp_gap) then use cache.
But note: the current_stamp we have might be stale (if the background job hasn't run recently). So we are trading off accuracy for performance.
Alternatively, we can design the cache to only use TTL and then have a separate mechanism for stamp?
But the requirement is bounded staleness by stamps.
Let me re-think: bounded staleness by stamps means that we are okay with a value that is at most N versions old. So if we don't know the current stamp, we cannot guarantee that.
So we must have a way to know the current stamp (or at least an upper bound on the current stamp) without querying the data source for every read.
Idea: Have a background process that periodically (every, say, 1 second) queries the data source for the current stamp and updates a global variable current_stamp. Then on read, we can check:
code
if (current_time < cache.expiry) and (current_stamp - cache.stamp <= max_stamp_gap) then use cache.
But note: the background process might be behind, so the current_stamp might be less than the true current stamp. Then we might be using a cache that is more stale than allowed?
Alternatively, we can have the data source push the current stamp? But that's not always possible.
Given the constraints, we might have to accept that we cannot have perfect bounded staleness by stamp without querying the data source on every read.
Let's consider a different approach:
We can have two types of reads:
code
1. Read that requires bounded staleness: we are willing to wait for a fresh value if the cache is too stale.
2. Read that can tolerate any staleness (but we still want to use cache if available and not too old by TTL).
But the problem says "bounded-staleness", so we must enforce the stamp bound.
So we must have the current stamp. Therefore, we have to query the data source for the current stamp on every read? That defeats the purpose of caching.
Alternatively, we can have a hybrid:
code
We cache both the value and the stamp. When we read, we check the TTL and if the TTL hasn't expired, we return the cached value. But we also check the stamp condition by comparing the cached stamp with the current stamp (which we get from a separate, cheap call to the data source that only returns the current stamp, not the full value).
So we can have:
code
Data source provides:
- get_current_stamp(): returns the current stamp (cheap, maybe from a in-memory variable or a lightweight call)
- get_value(): returns the current value and stamp (expensive)
Then:
code
On read:
if cache exists and (current_time < cache.expiry) and (current_stamp - cache.stamp <= max_stamp_gap):
return cache.value
else:
fetch the value (and stamp) from get_value(), update cache, and return.
This way, we only call get_value() when the cache is stale by TTL or by stamp. And we call get_current_stamp() on every read? That might be acceptable if get_current_stamp() is cheap.
But note: get_current_stamp() might not be cheap if it requires a network call. We can cache the current stamp with a very short TTL? But then we are back to the same problem.
Alternatively, we can have the data source push the current stamp to the cache? But that's not pull-based.
Given the complexity, let's assume that we have a way to get the current stamp cheaply (for example, the data source maintains the current stamp in a shared memory or a very fast in-process call). Then the design becomes:
Cache entry:
value
stamp
expiry (based on TTL)
Global:
current_stamp (updated by a background process or by the data source push, but we assume we can get it quickly)
Read:
if cache exists and (now < cache.expiry) and (current_stamp - cache.stamp <= max_stamp_gap):
return cache.value
else:
// We need to refresh. We might have multiple requests coming in at the same time, so we want to avoid thundering herd.
// We can use a lock or a single flight pattern.
code
lock the cache for this key (or use a single flight mechanism for the key)
// Check again inside the lock in case another request already refreshed.
if cache exists and (now < cache.expiry) and (current_stamp - cache.stamp <= max_stamp_gap):
return cache.value
else:
new_value, new_stamp = data_source.get_value()
cache.value = new_value
cache.stamp = new_stamp
cache.expiry = now + TTL
return new_value
But note: the condition (current_stamp - cache.stamp <= max_stamp_gap) uses the current_stamp we have (which might be slightly stale). We are accepting that the current_stamp might be a little behind, so we might be allowing a slightly larger gap?
Alternatively, we can adjust: we can require that the cached stamp is at least (current_stamp - max_stamp_gap). If our current_stamp is behind, then we might be too strict?
Actually, if our current_stamp is behind, then the real current stamp might be higher, so the gap might be larger than we think. So we might be using a cache that is too stale. But if we use a background process that updates current_stamp frequently, it might be acceptable.
Now, fairness: we want to avoid starvation. In the above, if the cache is constantly being refreshed by one request, other requests might wait for the lock. But note that we are using a lock per key, so only one request per key will be blocking. And once the cache is updated, all subsequent requests will use the cache until it becomes stale again.
However, if the cache is constantly becoming stale (because TTL is short or max_stamp_gap is small) then we might have frequent refreshes. But that's the requirement.
But what about fairness between keys? We are locking per key, so one key being hot doesn't block others.
Another fairness issue: if a request comes in and the cache is stale, it will block until the fetch is done. But if the fetch is slow, then subsequent requests for the same key will also block (until the first one finishes). That's the single flight pattern, which is good to avoid multiple fetches. But it might cause some requests to wait longer.
We can also consider returning the stale cache if we are within the TTL but not the stamp bound? But the requirement says bounded staleness, so we cannot.
Alternatively, we can have a "grace period" for the stamp? But that would break the bound.
So the above design seems acceptable.
Let's write the code structure:
We'll have a class for the cache entry and the cache.
We assume:
data_source.get_current_stamp() -> int
data_source.get_value() -> (value, stamp)
We'll use a mutex per key to avoid thundering herd.
We'll set:
TTL: time in seconds (or milliseconds)
max_stamp_gap: integer
Steps for get(key):
code
current_time = now()
current_stamp = data_source.get_current_stamp()
cache_entry = cache.get(key)
if cache_entry exists and (current_time < cache_entry.expiry) and (current_stamp - cache_entry.stamp <= max_stamp_gap):
return cache_entry.value
else:
lock = get_lock(key) // a mutex for this key
lock.lock()
try:
// double check after acquiring the lock
cache_entry = cache.get(key)
if cache_entry exists and (current_time < cache_entry.expiry) and (current_stamp - cache_entry.stamp <= max_stamp_gap):
return cache_entry.value
// else, we need to fetch
value, stamp = data_source.get_value()
// update cache
cache_entry = CacheEntry(value, stamp, current_time + TTL)
cache.put(key, cache_entry)
return value
finally:
lock.unlock()
But note: we are using the same current_time and current_stamp that we got at the beginning? What if the lock acquisition takes time? Then current_time might be old. We should update current_time and current_stamp after acquiring the lock?
However, if we update current_stamp after the lock, then we might have a situation where while we were waiting for the lock, the current_stamp advanced a lot. But that's okay because we are going to fetch anyway.
Alternatively, we can get the current_stamp and current_time inside the lock. But then every request that misses the cache will call get_current_stamp() even if they are going to wait for the lock. That might be acceptable if get_current_stamp() is cheap.
Let's adjust:
code
We get the current_stamp and current_time at the beginning, but then after we get the lock, we re-check the conditions with the same current_stamp and current_time? That might be problematic because time has passed.
Better:
code
So the algorithm:
code
def get(key):
current_time = now()
current_stamp = data_source.get_current_stamp()
cache_entry = cache.get(key)
if cache_entry and (current_time < cache_entry.expiry) and (current_stamp - cache_entry.stamp <= max_stamp_gap):
return cache_entry.value
lock = get_lock(key)
lock.lock()
try:
// Double check with updated time and stamp
current_time2 = now()
current_stamp2 = data_source.get_current_stamp()
cache_entry = cache.get(key)
if cache_entry and (current_time2 < cache_entry.expiry) and (current_stamp2 - cache_entry.stamp <= max_stamp_gap):
return cache_entry.value
// else, we must fetch
value, stamp = data_source.get_value()
cache_entry = CacheEntry(value, stamp, now() + TTL)
cache.put(key, cache_entry)
return value
finally:
lock.unlock()
This should be safe and fair.
But note: we are calling get_current_stamp() twice for a request that ends up fetching? That's acceptable if it's cheap.
If get_current_stamp() is expensive, we might want to avoid the second call. We can try:
code
We can remember the current_stamp from the first call and use it in the double-check? But then we might be using an old current_stamp and incorrectly think the cache is fresh?
Actually, if the current_stamp has increased, then the condition (current_stamp - cache_entry.stamp <= max_stamp_gap) might become false, so we would fetch. That's safe. But if the current_stamp has decreased? That shouldn't happen because stamps are increasing.
So if stamps are monotonically increasing, then using the old current_stamp (which is <= the new current_stamp) is safe because:
old_current_stamp - cache_entry.stamp <= max_stamp_gap => new_current_stamp - cache_entry.stamp might be larger, so we might fetch when we don't need to? That's safe but less efficient.
But we want to avoid fetching if the cache is still fresh. So we should use the latest current_stamp.
Therefore, if get_current_stamp() is cheap, we do it again. If not, we might have to live with the inefficiency.
Another idea: we can have a background process that updates the current_stamp and we read it from a shared variable (atomic). Then we don't need to call the data source for the current_stamp. But then we are back to the problem of the current_stamp being stale.
Given the requirement of bounded staleness, we must have a reasonably current current_stamp.
Let's assume that get_current_stamp() is a cheap operation (like reading a shared variable or a very fast in-memory call). Then the above design is acceptable.
Now, what about fairness? We are using a lock per key, so one key being hot doesn't block others. And within the same key, we are using single flight, so only one request will be fetching. The others will either use the cache (if it becomes fresh during the wait) or wait for the fetch and then use the fresh value.
This seems fair.
Edge cases:
code
- What if the data source's stamp doesn't increase? Then we might never refresh by stamp? But then the TTL will eventually cause a refresh.
- What if the data source's stamp jumps by more than max_stamp_gap? Then we will always be stale by stamp and we will fetch on every request? But note that after we fetch, we update the cache with the new stamp, so the next request might be within the gap? It depends.
Example:
max_stamp_gap = 5
cache.stamp = 10
current_stamp = 20 (so gap=10, which is >5) -> we fetch.
after fetch, cache.stamp = 20.
next request: current_stamp=20, gap=0 -> fresh.
So it's okay.
Implementation details:
code
We need a thread-safe cache (map) and a way to get a lock for a key.
We can use a sync.Mutex in Go, or a similar lock in other languages. We can have a map of mutexes, but we need to clean up unused mutexes? Or we can use a single lock for the entire cache? That would be a bottleneck.
Better: use a sharded lock or a lock per key. We can use a `sync.Map` in Go for the locks, or a `java.util.concurrent.ConcurrentHashMap` in Java.
We can also use a `singleflight` package (like in Go) to avoid duplicate fetches.
Let's write a pseudo-code in a generic way:
class BoundedStalenessCache:
TTL: duration
max_stamp_gap: int
cache: concurrent map from key to CacheEntry
lock_map: concurrent map from key to mutex // or use a singleflight group per key
code
get_current_stamp(): int // implemented by the data source
get(key):
current_time = now()
current_stamp = get_current_stamp()
entry = cache.get(key)
if entry and (current_time < entry.expiry) and (current_stamp - entry.stamp <= max_stamp_gap):
return entry.value
// Get the lock for this key
lock = lock_map.get_or_default(key, new_mutex)
lock.lock()
try:
// Double check
current_time2 = now()
current_stamp2 = get_current_stamp()
entry = cache.get(key)
if entry and (current_time2 < entry.expiry) and (current_stamp2 - entry.stamp <= max_stamp_gap):
return entry.value
// Fetch
value, stamp = data_source.get_value()
entry = CacheEntry(value, stamp, now() + TTL)
cache.put(key, entry)
return value
finally:
lock.unlock()
But note: we are holding the lock while calling data_source.get_value(), which might be slow. That's acceptable because we want to avoid multiple fetches for the same key.
However, we are also calling get_current_stamp() inside the lock. That's okay if it's cheap.
But what if get_current_stamp() is expensive and we have many keys? Then we are calling it for every miss. That might be acceptable.
Alternatively, we can have a background process that updates the current_stamp and we read it from an atomic variable. Then we don't need to call get_current_stamp() in the get() method. But then we have to manage the background process.
Given the requirement, I think the above design is a good starting point.
Let's consider if we can remove the second get_current_stamp() call by storing the current_stamp at the time we first checked and then using it in the double-check? But as discussed, it might be stale.
We can do:
code
current_stamp_before_lock = get_current_stamp()
... then in the lock, we use current_stamp_before_lock?
But if the current_stamp has increased, we might be too lenient? Actually, if the current_stamp has increased, then the gap (current_stamp_before_lock - entry.stamp) might be <= max_stamp_gap, but the real current_stamp might be larger. So we might be using a stale cache that is beyond the allowed gap.
So we must use the latest current_stamp.
Therefore, we have to call get_current_stamp() inside the lock if we want to be precise.
But note: the current_stamp might have changed between the first call and the lock. So we are already using a stale current_stamp in the first check. That's acceptable because we are going to lock and then re-check with a fresh one.
So the first check is just an optimization to avoid the lock if the cache is fresh.
In summary, the design is:
Cache entry: value, stamp, expiry.
On read, get current time and current stamp (cheaply).
If cache entry exists and is fresh by both TTL and stamp gap, return.
Otherwise, lock for the key, then re-check with updated time and stamp (to avoid race with another updater).
If still stale, fetch from data source, update cache, and return.
This ensures bounded staleness and fairness (via single flight per key).
Now, what about the TTL? We set the expiry when we update the cache. But note: if the data source's stamp updates very frequently, we might be updating the cache very often. But that's the requirement.
We can also consider having a background job that refreshes the cache before it expires? But that's an optimization.
This design should work.
Let me write a more concrete example in Python-like code:
We'll use a threading.Lock for each key.
Note: In Python, we can use a dictionary of locks, but we have to be careful about memory leaks. We can use a weakref dictionary or clean up locks after use.
Alternatively, we can use a single lock for the entire cache, but that would be a bottleneck.
We can use a sharded lock: have an array of locks and use hash(key) % N to pick a lock. That reduces contention but doesn't eliminate it.
For simplicity, we'll do a lock per key.
Code:
import time
import threading
class CacheEntry:
def init(self, value, stamp, expiry):
self.value = value
self.stamp = stamp
self.expiry = expiry
def _get_lock(self, key):
with self.lock_map_lock:
if key not in self.lock_map:
self.lock_map[key] = threading.Lock()
return self.lock_map[key]
def get(self, key):
current_time = time.time()
current_stamp = self.data_source.get_current_stamp()
entry = self.cache.get(key)
if entry and current_time < entry.expiry and (current_stamp - entry.stamp) <= self.max_stamp_gap:
return entry.value
lock = self._get_lock(key)
with lock:
# Double check
current_time2 = time.time()
current_stamp2 = self.data_source.get_current_stamp()
entry = self.cache.get(key)
if entry and current_time2 < entry.expiry and (current_stamp2 - entry.stamp) <= self.max_stamp_gap:
return entry.value
# Fetch new value
value, stamp = self.data_source.get_value()
expiry = time.time() + self.ttl
self.cache[key] = CacheEntry(value, stamp, expiry)
return value
This is a basic implementation.
However, note that the data_source.get_current_stamp() and data_source.get_value() are called without any protection. We assume they are thread-safe.
Also, we are not cleaning up the lock_map. We might want to remove locks that are no longer used. We can use a WeakValueDictionary or a reference counting? Alternatively, we can use a fixed set of locks (sharding) and not worry about per-key locks.
Given the complexity, for production we might use a sharded lock or a singleflight package that handles the cleanup.
But for the purpose of this design, we have the core algorithm.
Let me know if you have any questions.
I'll design a bounded-staleness cache with stamps, TTLs, and fairness guarantees. This is a sophisticated caching pattern that balances freshness, performance, and fairness.
Core Design: Triple-Stamp Cache
1. Data Structures
python
from dataclasses import dataclass
from typing import Any, Optional, Dict, Tuple
import time
import threading
from collections import OrderedDict
import heapq
@dataclass
class CacheEntry:
"""Cache entry with multiple timestamp/version controls"""
value: Any
# Stamps (logical timestamps/versions)
logical_stamp: int # Monotonically increasing version
observed_stamp: int # Stamp when data was fetched
# Physical timestamps
fetch_time: float # When this entry was fetched
expiry_time: float # TTL-based expiry
# Fairness tracking
wait_start: Optional[float] = None # When request started waiting
request_count: int = 0 # How many requests waited for this
class BoundedStalenessCache:
def __init__(
self,
max_staleness: float, # Max allowed staleness in seconds
ttl: float, # Hard TTL in seconds
max_stamp_gap: int = 10, # Max allowed stamp gap
fairness_window: int = 100, # Requests to consider for fairness
eviction_policy: str = "lru" # "lru", "fifo", or "staleness"
):
self.max_staleness = max_staleness
self.ttl = ttl
self.max_stamp_gap = max_stamp_gap
self.fairness_window = fairness_window
# Main storage (thread-safe)
self._cache: Dict[str, CacheEntry] = {}
self._cache_lock = threading.RLock()
# Fairness tracking
self._wait_queue: Dict[str, list] = {} # key -> [(timestamp, request_id)]
self._recent_waits: OrderedDict = OrderedDict() # LRU of recent waits
self._fairness_counter = 0
self._fairness_lock = threading.Lock()
# Global stamps (from data source)
self._current_logical_stamp = 0
self._last_stamp_update = 0
self._stamp_lock = threading.Lock()
# Background maintenance
self._stop = False
self._maintenance_thread = threading.Thread(
target=self._maintenance_worker,
daemon=True
)
self._maintenance_thread.start()
2. Staleness Calculation Logic
python
def _is_fresh(self, entry: CacheEntry,
current_logical_stamp: int,
current_time: float) -> Tuple[bool, str]:
"""
Check if cache entry is fresh enough.
Returns (is_fresh, reason) where reason is:
- "fresh": entry is within both TTL and stamp bounds
- "ttl_expired": TTL exceeded
- "stamp_stale": stamp gap too large
- "combined": both expired
"""
reasons = []
# Check TTL (hard bound)
if current_time >= entry expiry_time:
reasons.append("ttl_expired")
# Check logical stamp gap (bounded staleness)
stamp_gap = current_logical_stamp - entry.observed_stamp
if stamp_gap > self.max_stamp_gap:
reasons.append("stamp_stale")
is_fresh = len(reasons) == 0
reason = "fresh" if is_fresh else "_".join(reasons)
return is_fresh, reason
3. Fairness-Aware Fetching with Single Flight
python
def get(self, key: str,
force_refresh: bool = False) -> Tuple[Any, Dict[str, Any]]:
"""
Get value with fairness guarantees.
Returns (value, metadata) where metadata includes:
- 'stale': bool (was cache stale)
- 'waited': float (seconds waited)
- 'stamp_gap': int (current stamp gap)
- 'freshness_age': float (seconds since fetch)
"""
current_time = time.time()
current_logical_stamp = self._get_current_logical_stamp()
request_id = f"{time.time()}_{threading.get_ident()}"
# Fast path: try cache without lock
with self._cache_lock:
entry = self._cache.get(key)
if entry and not force_refresh:
is_fresh, reason = self._is_fresh(
entry, current_logical_stamp, current_time
)
if is_fresh:
return entry.value, self._metadata(
entry, current_time, current_logical_stamp,
waited=0, was_stale=False
)
# Slow path: need to refresh with fairness
wait_start = current_time
lock = self._get_or_create_lock(key)
with lock:
# Double-check after acquiring lock
entry = self._cache.get(key)
if entry and not force_refresh:
is_fresh, reason = self._is_fresh(
entry, current_logical_stamp, time.time()
)
if is_fresh:
return entry.value, self._metadata(
entry, time.time(), current_logical_stamp,
waited=0, was_stale=False
)
# Register in wait queue for fairness tracking
self._register_wait(key, request_id, wait_start)
try:
# Actually fetch from source
value, new_logical_stamp = self._fetch_from_source(key)
# Update cache
new_entry = CacheEntry(
value=value,
logical_stamp=new_logical_stamp,
observed_stamp=new_logical_stamp,
fetch_time=time.time(),
expiry_time=time.time() + self.ttl,
wait_start=None,
request_count=0
)
with self._cache_lock:
self._cache[key] = new_entry
self._update_stamp(new_logical_stamp)
# Calculate wait time
waited = time.time() - wait_start
# Update fairness metrics
self._record_successful_fetch(key, request_id, waited)
return value, self._metadata(
new_entry, time.time(), new_logical_stamp,
waited=waited, was_stale=True
)
finally:
self._unregister_wait(key, request_id)
4. Fairness Algorithm: Credit-Based Scheduling
python
def _register_wait(self, key: str, request_id: str, timestamp: float):
"""Register request waiting for key"""
with self._fairness_lock:
if key not in self._wait_queue:
self._wait_queue[key] = []
heapq.heappush(self._wait_queue[key], (timestamp, request_id))
# Track in recent waits for fairness calculation
self._recent_waits[request_id] = {
'key': key,
'start': timestamp,
'position': len(self._wait_queue[key])
}
if len(self._recent_waits) > self.fairness_window * 2:
self._recent_waits.popitem(last=False)
def _should_skip_refresh(self, key: str) -> bool:
"""
Fairness check: should we skip refresh to give priority to
long-waiting requests?
"""
with self._fairness_lock:
if key not in self._wait_queue:
return False
# Check if there are older requests waiting
queue = self._wait_queue[key]
if not queue:
return False
oldest_time, oldest_id = queue[0]
age = time.time() - oldest_time
# If oldest request waited too long, give it priority
if age > self.max_staleness / 2:
return True
# Check recent wait distribution
recent_waits = [
w for w in self._recent_waits.values()
if w['key'] == key
]
if recent_waits:
avg_wait = sum(time.time() - w['start'] for w in recent_waits) / len(recent_waits)
if avg_wait > self.max_staleness / 4:
return True
return False
5. Background Maintenance Worker
python
def _maintenance_worker(self):
"""Background thread for cache maintenance and fairness"""
while not self._stop:
try:
current_time = time.time()
# 1. Eviction based on policy
self._evict_stale_entries(current_time)
# 2. Proactive refresh for hot keys (optional)
self._proactive_refresh(current_time)
# 3. Clean up dead wait queues
self._cleanup_wait_queues(current_time)
# 4. Update global stamp if needed
self._sync_logical_stamp()
except Exception as e:
# Log error but continue
pass
time.sleep(0.1) # Check every 100ms
def _evict_stale_entries(self, current_time: float):
"""Evict entries based on policy"""
with self._cache_lock:
keys_to_evict = []
current_logical_stamp = self._get_current_logical_stamp()
for key, entry in self._cache.items():
is_fresh, reason = self._is_fresh(
entry, current_logical_stamp, current_time
)
if not is_fresh:
keys_to_evict.append(key)
for key in keys_to_evict:
del self._cache[key]
# If too many entries, evict by chosen policy
if len(self._cache) > self.fairness_window * 10:
self._evict_by_policy()
def _evict_by_policy(self):
"""Evict entries based on configured policy"""
if self.eviction_policy == "staleness":
# Evict entries with largest stamp gap + age
entries = []
current_logical_stamp = self._get_current_logical_stamp()
current_time = time.time()
for key, entry in self._cache.items():
stamp_age = current_logical_stamp - entry.observed_stamp
time_age = current_time - entry.fetch_time
combined_score = stamp_age + (time_age / self.ttl)
entries.append((combined_score, key))
entries.sort(reverse=True) # Worst first
for _, key in entries[:len(self._cache)//4]:
del self._cache[key]
elif self.eviction_policy == "lru":
# Standard LRU eviction
# (would need access tracking)
pass
6. Stamp Management
python
def _get_current_logical_stamp(self) -> int:
"""Get current logical stamp from data source"""
with self._stamp_lock:
return self._current_logical_stamp
def _update_stamp(self, new_stamp: int):
"""Update global logical stamp"""
with self._stamp_lock:
if new_stamp > self._current_logical_stamp:
self._current_logical_stamp = new_stamp
self._last_stamp_update = time.time()
def _sync_logical_stamp(self):
"""Background sync with data source for stamp"""
# In real implementation, query data source periodically
# For now, just check if we need to update
pass
7. Metadata & Monitoring
python
def _metadata(self, entry: CacheEntry, current_time: float,
current_stamp: int, waited: float, was_stale: bool) -> Dict[str, Any]:
"""Generate metadata about cache access"""
return {
'stale': was_stale,
'waited_seconds': waited,
'stamp_gap': current_stamp - entry.observed_stamp,
'freshness_age': current_time - entry.fetch_time,
'ttl_remaining': max(0, entry.expiry_time - current_time),
'cache_hit': not was_stale
}
def get_stats(self) -> Dict[str, Any]:
"""Get cache statistics including fairness metrics"""
with self._fairness_lock:
wait_times = [
time.time() - w['start']
for w in self._recent_waits.values()
]
return {
'size': len(self._cache),
'avg_wait_time': sum(wait_times) / len(wait_times) if wait_times else 0,
'max_wait_time': max(wait_times) if wait_times else 0,
'waiting_requests': sum(len(q) for q in self._wait_queue.values()),
'fairness_score': self._calculate_fairness_score()
}
def _calculate_fairness_score(self) -> float:
"""
Calculate fairness score (0-1) based on:
- Variance of wait times
- Maximum wait time vs max_staleness
- Distribution of waits across keys
"""
# Implementation would analyze wait distribution
# Simple version: 1 - (max_wait / max_staleness)
# Clamped to [0, 1]
pass
8. Configuration & Usage Example
python
# Example configuration
cache = BoundedStalenessCache(
max_staleness=5.0, # Max 5 seconds staleness
ttl=30.0, # Hard 30 second TTL
max_stamp_gap=10, # Max 10 versions behind
fairness_window=200, # Track last 200 requests per key
eviction_policy="staleness"
)
# Usage
def get_user_data(user_id: str):
value, meta = cache.get(f"user:{user_id}")
print(f"Waited {meta['waited_seconds']:.3f}s, "
f"stale: {meta['stale']}, "
f"stamp_gap: {meta['stamp_gap']}")
return value
# Force refresh
value, meta = cache.get("some_key", force_refresh=True)
Key Design Decisions & Trade-offs
Staleness Guarantees
TTL Bound: Absolute maximum age (hard bound)
Stamp Gap Bound: Logical version difference (bounded staleness)
Persist Stamps: Save/restore logical stamps across restarts
WAN-Aware: Consider network latency in staleness calculations
This design provides strict bounded staleness (both temporal and logical), fairness guarantees (no starvation), and efficient concurrent access while being practically implementable in most languages. The key insight is treating logical stamps and physical time as orthogonal dimensions of staleness, and using per-key queues with aging to ensure fairness.
We do:
current_time = now()
current_stamp = data_source.get_current_stamp()
... then check without lock.
If we decide to lock, then after locking, we should re-get the current_time and current_stamp? But note: we are going to fetch anyway, so we can just fetch without re-checking?
However, in the double-check after lock, we use the old current_time and current_stamp? That might be too old.
Let me re-think the double-check:
We want to avoid the situation where two requests both find the cache stale and both try to fetch. So we do:
Request1: check cache, stale -> lock -> double check (with old current_time and current_stamp) -> still stale? -> fetch.
Request2: check cache, stale -> try lock (blocked) -> when it gets the lock, it does double check.
But during the time Request1 was waiting for the lock, the cache might have been updated by another process? No, because we are the only one holding the lock.
However, the current_time and current_stamp we used in the double-check are the ones we got before locking. That means that if the cache was updated by a background process (not through our lock) then our double-check might be using stale current_stamp and current_time.
But note: the cache update only happens in the lock, so if we are holding the lock, no one else can update. But what if the cache is updated by a different process that doesn't use our lock? Then we have a problem.
We are assuming that all updates to the cache go through this get() method (with the lock). But if there are other ways to update the cache (like a background refresh) then we need to coordinate.
Alternatively, we can avoid the double-check and just fetch after acquiring the lock? But then we might fetch even if the cache became fresh in the meantime.
So we do:
After getting the lock, we re-read the cache and re-check the conditions with the current time and current stamp (which we get again?).
But note: we are in a locked section, so we can safely read the cache and then decide to fetch.
We can do:
lock.lock()
try:
// Re-fetch current_time and current_stamp?
current_time2 = now()
current_stamp2 = data_source.get_current_stamp()
cache_entry = cache.get(key)
if cache_entry exists and (current_time2 < cache_entry.expiry) and (current_stamp2 - cache_entry.stamp <= max_stamp_gap):
return cache_entry.value
// else fetch
value, stamp = data_source.get_value()
cache_entry = CacheEntry(value, stamp, now() + TTL) // note: we use the current time after fetching
cache.put(key, cache_entry)
return value
finally:
lock.unlock()
But wait: we are calling get_current_stamp() inside the lock. That might be acceptable if it's cheap, but if it's expensive we are doing it for every request that misses the cache and then again for the one that gets the lock.
Alternatively, we can rely on the fact that the cache is only updated in the lock, so the cache_entry we see inside the lock is the same as the one we saw outside? Not necessarily, because another process might have updated the cache and then released the lock, and then we acquired the lock. But if we are using the same lock for the same key, then only one process can update at a time.
However, if we have multiple processes (or threads) and the same key, then the lock is per key and we are safe.
But what about the current_stamp? It might have changed between the first check and the lock. So we should re-check with the latest current_stamp.
So we do need to get the current_stamp again inside the lock.
But then we are calling get_current_stamp() twice for the request that gets the lock? That might be acceptable.
Alternatively, we can pass the current_stamp and current_time from outside and then re-check with the same ones? But that might be too old.
Given that the time between the first check and acquiring the lock might be significant, we should update.
So:
Step1: without lock, check with current_time and current_stamp. If fresh, return.
Step2: if not, lock and then re-check with updated current_time and current_stamp.
But note: if the cache is being updated very frequently, we might have:
Request1: check (stale) -> lock -> re-check (still stale) -> fetch.
Request2: check (stale) -> wait for lock -> lock -> re-check (now fresh because Request1 updated) -> return.
That's good.