typescript 46 lines · 7 steps

A sliding window rate counter in TypeScript

A fixed ring of time buckets tracks event counts over a moving window without ever growing unbounded.

Explained by highlit
1type Bucket = { start: number; count: number };
2 
3export class SlidingWindowCounter {
4 private readonly windowMs: number;
5 private readonly bucketMs: number;
6 private readonly buckets: Bucket[];
7 
8 constructor(windowMs: number, bucketCount = 60) {
9 if (windowMs <= 0 || bucketCount <= 0) {
10 throw new RangeError("windowMs and bucketCount must be positive");
11 }
12 this.windowMs = windowMs;
13 this.bucketMs = Math.ceil(windowMs / bucketCount);
14 this.buckets = Array.from({ length: bucketCount }, () => ({ start: 0, count: 0 }));
15 }
16 
17 private slotFor(now: number): Bucket {
18 const index = Math.floor(now / this.bucketMs) % this.buckets.length;
19 const bucketStart = now - (now % this.bucketMs);
20 const slot = this.buckets[index];
21 if (slot.start !== bucketStart) {
22 slot.start = bucketStart;
23 slot.count = 0;
24 }
25 return slot;
26 }
27 
28 record(now = Date.now(), amount = 1): void {
29 this.slotFor(now).count += amount;
30 }
31 
32 count(now = Date.now()): number {
33 const cutoff = now - this.windowMs;
34 let total = 0;
35 for (const bucket of this.buckets) {
36 if (bucket.start > cutoff) {
37 total += bucket.count;
38 }
39 }
40 return total;
41 }
42 
43 ratePerSecond(now = Date.now()): number {
44 return this.count(now) / (this.windowMs / 1000);
45 }
46}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A fixed-size ring of buckets keyed by time gives O(bucketCount) memory regardless of event volume.
  2. 2Reusing a slot whose `start` no longer matches lets you lazily reset stale buckets without a background sweep.
  3. 3Summing only buckets newer than a cutoff approximates a sliding window while keeping writes O(1).

Related explainers

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps
typescript
import { useEffect, useState } from "react";
 
interface Section {
  id: string;

Building a scroll-spy hook in React

custom-hooks intersectionobserver dom-observation
Intermediate 8 steps
python
import secrets
 
from django.contrib.auth import authenticate, login
from django.core.cache import cache

Two-factor login with OTP in Django

two-factor-auth one-time-passwords caching
Intermediate 9 steps

Share this explainer

Here's the card — post it anywhere.

A sliding window rate counter in TypeScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code