Date: <IMF-fixdate> per RFC 9110 §6.6.1 / RFC 5322 §3.3:
Sun, 06 Nov 1994 08:49:37 GMT ; 29 bytes, fixed width
Naive implementations call time(NULL) + gmtime_r(...) + strftime(...)
once per response, paying ~3 syscalls / library calls + a TZ lookup on
every keep-alive request. Under TFB plaintext at 220K req/s + 4 workers,
that's ~880K Date-header formats / s — measurable.
This cache amortises the formatting cost to once per second per
worker: each access compares a cached "epoch second" against the
current CLOCK_REALTIME second; on a miss it re-formats the buffer
in place, on a hit it returns the same 29-byte buffer immediately.
Per-worker, not shared: each reactor worker holds its own DateCache
in worker-local storage. There is no cross-thread contention, no atomic,
no mutex. The trade-off is num_workers formats / s instead of one;
at typical worker counts (1–32) that's negligible.
Algorithm: branch-free Howard Hinnant civil_from_days inverse for
the year/month/day decomposition (same routine
flare.http.structured_logger uses for ISO-8601 timestamps and
flare.http.conditional uses for HTTP-date parsing), then a 29-byte
direct write into a stack / heap buffer. No allocations on the hot
path past first construction.
The cache exposes current_bytes (returns a borrow over the cached
buffer) and current_string (allocates a fresh String copy when
the caller needs ownership). Middleware that emits Date headers
into a wire buffer should prefer current_bytes to avoid a per-
request copy — the underlying 29-byte buffer is stable until the
next refresh() call from the same worker.
Example:
var cache = DateCache()
cache.refresh() # idempotent; no-op when already on the current second
var buf = cache.current_bytes() # Span[UInt8, ...]
# ... copy buf into wire buffer with memcpy ...
The cache is not thread-safe. Each worker constructs its own.