跳到正文
产品桌面工具TASTECAD图纸查看TASTEFILES文件管理TASTEFTP文件传输TASTESSH远程工作空间TASTEZIP压缩与解压TASTEWINM文件管理开发工具TASTECODERust 集成开发环境TASTESTUDIO集成开发与测试环境TASTEETL数据整合(ETL)服务器TASTEREMOTE远程桌面服务器TASTEGEO空间信息服务器TASTEMAIL邮件工作空间投资TASTESTOCK股票自动交易桌面应用开始使用下载文档购买全部产品
市场
资讯
技术资讯今日开发资讯开发文档编程语言RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular服务端框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express应用与桌面框架TauriFlutterReact NativeElectron算法算法基础核心算法进阶算法实用算法
社区项目开发日志提示词AI 工具问题作品展示社区指南
合作技术传授网站构建桌面应用构建发布与支付流水线销售合作伙伴联系我们
服务远程桌面安装包定制
TASTEDEV
产品

桌面工具

TASTECAD复杂图纸,轻松打开TASTEFILES只要需要的文件,最快送达TASTEFTP让文件往来,干净利落TASTESSH你与服务器之间,连接更牢靠TASTEZIP压得更快,解得更稳TASTEWINM以键盘为主、用两个窗格整理文件的文件管理器

开发工具

TASTECODE在一个窗口中完成 Rust 应用的编辑、构建、调试和测试TASTESTUDIO从编辑到远程测试,再到经批准的 AI 修复TASTEETL边看数值,边搬数据

服务器

TASTEREMOTE在自己的服务器上运行的远程桌面TASTEGEO用 Rust 重新构建兼容 GeoServer 的空间信息服务器TASTEMAIL把邮件的主导权拿回自己手中

投资

TASTESTOCK何时、做什么——按你定下的规则运行的股票自动交易

开始使用

下载所有产品的最新版本文档各产品使用方法购买订阅与永久许可全部产品一览全部产品
全部产品
市场资讯
技术

资讯

今日开发资讯语言、框架、GitHub 与 AI 官方发布开发文档语言、框架与算法指南

编程语言

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

框架

Web 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular
服务端框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express
应用与桌面框架TauriFlutterReact NativeElectron

算法

算法基础复杂度分析 · 排序 · 查找 · 基础数据结构 · 树与堆核心算法图遍历 · 最短路径与最小生成树 · 动态规划 · 贪心算法 · 分治法 · 回溯法进阶算法字符串算法 · 数学与数论 · 位运算 · 线段树 · 并查集实用算法编程面试解题策略 · LRU 缓存 · 限流 · 一致性哈希
查看全部开发文档
社区
项目发现开发者与作品开发日志决策与试错提示词可复用的指令AI 工具问题Claude、Codex、Gemini 的问题与变通办法作品展示已完成的成果社区指南我们如何公开构建
合作
技术传授用 Rust 和 egui 打造原生应用网站构建10 种语言、账户、文档与下载桌面应用构建Rust 和 egui,不用 WebView发布与支付流水线签名、MSI、deb、rpm、AppImage、哈希销售合作伙伴推荐即得 30%联系我们开发、合作与投资咨询
服务
远程桌面用浏览器连接你的电脑安装包定制只装需要的,设置预先放好
购买
ZH
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
登录
登录
TASTEDEV

从小工具到更好的开发。

support@tastedev.net支持 TASTEDEV
产品产品线购买文档下载市场客户支持
社区项目开发日志提示词AI 工具问题作品展示
政策关于我们隐私政策服务条款订阅条款退款政策社区规范
账户登录注册
访客
今天
昨天
累计浏览
公司名称
GXSOFT
法定代表人
CHOI YOUNG GU
营业执照号
853-44-00368
地址
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
电话
+82-10-4404-1523
电子邮件
whitecalvin@tastedev.net
个人信息保护负责人
CHOI YOUNG GU

© 2026 TASTEDEV产品信息以已验证的开发源码为准。已发布·持续改进

限流 文档
限流
ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
讨论

限流 指南 · 2/6

How It Works

本章目前仅提供英文版。

This chapter traces small examples to show, step by step, how each of the five algorithms accepts and rejects requests, which makes it easier to judge which one fits a given situation.

Fixed window and the boundary problem

A fixed window with a limit of "5 per minute" keeps one counter per window number, which is the timestamp divided by 60. When the window changes, the counter starts again from zero. The trouble is the boundary.

TimeWindowCounterResult
0:59.0 to 0:59.9 (5 requests)01 to 5all allowed
1:00.0 to 1:00.9 (5 requests)11 to 5all allowed
1:01.016rejected

Ten requests got through in about two seconds: twice the limit, if the intent was "never more than 5 in any 60 seconds". Sliding windows fix this.

Sliding window log

Keep the timestamps of accepted requests in a deque. On each request, drop timestamps that have fallen out of the window from the front, then count what remains. The limit here is "3 per 10 seconds".

TimeDroppedLog afterResult
1none[1]allowed
2none[1, 2]allowed
3none[1, 2, 3]allowed
5none[1, 2, 3]rejected (already 3)
111[2, 3, 11]allowed
122[3, 11, 12]allowed

The window is (now - 10, now], so at time 11 the entry at 1 expires. No 10-second span ever contains more than 3 accepted requests, so the limit is exact.

from collections import deque


def sliding_log(times: list[float], limit: int, window: float) -> list[bool]:
    log: deque[float] = deque()
    result = []
    for now in times:
        while log and log[0] <= now - window:
            log.popleft()                 # forget entries outside the window
        if len(log) < limit:
            log.append(now)               # only accepted requests are logged
            result.append(True)
        else:
            result.append(False)
    return result


print(sliding_log([1, 2, 3, 5, 11, 12], limit=3, window=10))
# [True, True, True, False, True, True]
对本章有疑问?
上一章Concepts下一章Implementation

Sliding window counter

Instead of a log, keep just two counters: the previous window and the current one. Assume the previous window's requests were spread evenly, and count only the fraction of it that still overlaps the last 60 seconds.

estimate = previous count × (1 - time into current window / window length) + current count

With a limit of "10 per 60 seconds", 8 requests in the previous window (0 to 60 s) and 3 so far in the current one (60 to 120 s):

TimePrevious weightEstimateResultCurrent count
751 - 15/60 = 0.758 × 0.75 + 3 = 9.0allowed4
761 - 16/60 ≈ 0.7335.87 + 4 = 9.87allowed5
801 - 20/60 ≈ 0.6675.33 + 5 = 10.33rejected5
1051 - 45/60 = 0.252.0 + 5 = 7.0allowed6

As time passes the previous window fades out. If its traffic was bunched at one end the estimate is slightly off, but each key needs only two numbers.

Token bucket

Tokens flow into the bucket at rate per second, up to capacity. Each request takes one token and is rejected when fewer than one remains. No timer is needed: when a request arrives, add "time since last check × rate" in one go (lazy refill).

Let us trace rate = 1 per second and capacity = 3.

TimeTokens after refillResultTokens left
0.03.0allowed2.0
0.22.2allowed1.2
0.41.4allowed0.4
0.60.6rejected0.6
1.51.5allowed0.5
3.52.5allowed1.5
3.61.6allowed0.6
3.70.7rejected0.7

The bucket starts full, so a burst of three passes within 0.4 seconds, after which the client is held to one request per second. After a quiet period the bucket refills and absorbs the next burst.

def token_bucket(times: list[float], rate: float, capacity: float) -> list[bool]:
    tokens, last = capacity, times[0] if times else 0.0
    result = []
    for now in times:
        tokens = min(capacity, tokens + (now - last) * rate)   # lazy refill
        last = now
        if tokens >= 1:
            tokens -= 1
            result.append(True)
        else:
            result.append(False)
    return result


print(token_bucket([0, 0.2, 0.4, 0.6, 1.5, 3.5, 3.6, 3.7], rate=1, capacity=3))
# [True, True, True, False, True, True, True, False]

Leaky bucket

Picture a bucket with a hole in the bottom. Incoming requests are placed in a fixed-size queue, and a worker takes them out at a constant rate. When the queue is full, new requests are dropped. With a queue of 3 and one request processed per second, five requests arriving together at time 0 result in three queued and two rejected; the queued ones are handled at 1, 2 and 3 seconds.

from collections import deque


def leaky_bucket(arrivals: list[int], queue_size: int, leak_per_tick: int) -> None:
    queue: deque[int] = deque()
    for tick, count in enumerate(arrivals):
        for _ in range(leak_per_tick):           # drain at a constant rate first
            if queue:
                print(f"t={tick}: processed request {queue.popleft()}")
        for i in range(count):                   # accept new work only if there is room
            if len(queue) < queue_size:
                queue.append(tick * 100 + i)
            else:
                print(f"t={tick}: rejected request {tick * 100 + i}")


leaky_bucket([5, 0, 0, 0], queue_size=3, leak_per_tick=1)

Unlike a token bucket, output never exceeds the rate, which makes it a good fit for shielding a downstream system that needs a steady pace. The cost is latency while requests wait in the queue. Note that the "meter" form of the leaky bucket, which measures without queueing, makes exactly the same decisions as a token bucket.

Summary

  • A fixed window is simple, but up to twice the limit can pass around a boundary.
  • A sliding window log is exact; a sliding window counter approximates it with two numbers.
  • A token bucket enforces an average rate while allowing bursts up to its capacity.
  • A leaky bucket smooths output with a queue at the cost of waiting time.

0 条评论

热门评论最新优先

登录 · 登录后即可发表评论。