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 class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
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.