php 55 lines · 9 steps

Debouncing session writes with an event loop

A store that coalesces rapid session updates into one atomic disk write per session using cancellable timers.

Explained by highlit
1final class DebouncedSessionStore
2{
3 private array $pending = [];
4 private array $timers = [];
5 
6 public function __construct(
7 private string $directory,
8 private float $delay = 0.5,
9 ) {}
10 
11 public function write(string $sessionId, array $data): void
12 {
13 $this->pending[$sessionId] = $data;
14 
15 if (isset($this->timers[$sessionId])) {
16 Loop::cancelTimer($this->timers[$sessionId]);
17 }
18 
19 $this->timers[$sessionId] = Loop::addTimer(
20 $this->delay,
21 fn () => $this->flush($sessionId),
22 );
23 }
24 
25 public function flush(string $sessionId): void
26 {
27 if (!array_key_exists($sessionId, $this->pending)) {
28 return;
29 }
30 
31 $data = $this->pending[$sessionId];
32 unset($this->pending[$sessionId], $this->timers[$sessionId]);
33 
34 $path = $this->pathFor($sessionId);
35 $tmp = $path . '.' . bin2hex(random_bytes(6)) . '.tmp';
36 
37 file_put_contents($tmp, serialize($data), LOCK_EX);
38 rename($tmp, $path);
39 }
40 
41 public function flushAll(): void
42 {
43 foreach (array_keys($this->pending) as $sessionId) {
44 if (isset($this->timers[$sessionId])) {
45 Loop::cancelTimer($this->timers[$sessionId]);
46 }
47 $this->flush($sessionId);
48 }
49 }
50 
51 private function pathFor(string $sessionId): string
52 {
53 return $this->directory . '/sess_' . preg_replace('/[^A-Za-z0-9]/', '', $sessionId);
54 }
55}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Debouncing trades write frequency for freshness by resetting a timer on every incoming change.
  2. 2Writing to a temp file then renaming gives an atomic swap that never leaves a half-written session on disk.
  3. 3Any buffered-write component needs an explicit flush path so pending data survives shutdown.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Debouncing session writes with an event loop — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code