Design Hit Counter
Problem (yeniden ifade)
Tamsayı zaman damgalarında (saniye) hit kaydet. getHits(t), t dahil geçmiş 300 saniyedeki hit’leri döndürür (yani (t-300, t]).
Sezgi
Hit zamanlarının kuyruğu; getHits’te zaman damgaları ≤ t-300 olanları düş.
Yaklaşımlar
Zaman damgası kuyruğu (300s)
DoğrulanmadıFikir. hit enqueue eder; getHits front ≤ t-300 iken dequeue; size döndür.
Yürüyüş. hit 1,2,3; getHits(4)=3; hit 300; getHits(300)=4; getHits(301)=3.
Trade-off. Boyu 300 bucket dizileri, saniyede çok hit olan yüksek QPS altında daha iyi ölçeklenir.
export class HitCounter {
private q: number[] = [];
private head = 0;
hit(timestamp: number): void {
this.q.push(timestamp);
}
getHits(timestamp: number): number {
while (this.head < this.q.length && this.q[this.head]! <= timestamp - 300) this.head++;
// Reclaim the consumed prefix so a long-running stream stays bounded.
if (this.head > 0 && this.head * 2 >= this.q.length) {
this.q = this.q.slice(this.head);
this.head = 0;
}
return this.q.length - this.head;
}
}
export class HitCounter {
private q: number[] = [];
private head = 0;
hit(timestamp: number): void {
this.q.push(timestamp);
}
getHits(timestamp: number): number {
while (this.head < this.q.length && this.q[this.head]! <= timestamp - 300) this.head++;
// Reclaim the consumed prefix so a long-running stream stays bounded.
if (this.head > 0 && this.head * 2 >= this.q.length) {
this.q = this.q.slice(this.head);
this.head = 0;
}
return this.q.length - this.head;
}
}
Şablon bağlantısı
Zaman pencereli kuyruk: hit zaman damgasını iter, getHits ön ≤ t - 300 oldukça onu düşürür. Kalan uzunluk cevaptır. Zaman damgaları artan sırada geldiği için yalnızca önün süresi dolabilir.
Yansıma
getHits300 saniyeden eski zaman damgalarını önden atar. Pencere(t-300, t].- Aynı timestamp birden fazla hit: her hit ayrı kayıt mı, sayaç mı? Bellek farkı ne?
- Zaman azalmaz (garanti). Garanti yoksa kuyruk yetmez.