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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Debouncing trades write frequency for freshness by resetting a timer on every incoming change.
- 2Writing to a temp file then renaming gives an atomic swap that never leaves a half-written session on disk.
- 3Any buffered-write component needs an explicit flush path so pending data survives shutdown.
Related explainers
php
<?php namespace App\Http\Controllers;
Streaming a filtered CSV export in Laravel
streaming
csv-export
query-builder
Intermediate
9 steps
php
<?php namespace App\Http\Middleware;
Idempotent requests with Laravel middleware
idempotency
middleware
caching
Advanced
8 steps
typescript
type ResizeCallback = (size: { width: number; height: number }) => void; export function observeResize(callback: ResizeCallback, delay = 150) { let timeoutId: ReturnType<typeof setTimeout> | undefined;
Debouncing window resize in TypeScript
debounce
closures
event-listeners
Intermediate
6 steps
php
<?php namespace App\Services;
Batch image resizing with PHP GD
image-processing
constructor-promotion
match-expression
Intermediate
10 steps
javascript
const MAX_BATCH_SIZE = 20; const FLUSH_INTERVAL = 5000; const ENDPOINT = '/api/analytics';
Batching analytics events in the browser
batching
buffering
sendbeacon
Intermediate
10 steps
php
<?php namespace App\Cache;
A content-hashed fragment cache in PHP
caching
content-hashing
atomic-writes
Intermediate
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/debouncing-session-writes-with-an-event-loop-explained-php-895f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.