Skip to content
Server Plugin

速率限制

必要相依性: io.ktor:ktor-server-rate-limit

程式碼範例: rate-limit

原生伺服器Ktor 支援 Kotlin/Native,可讓您在無需額外執行階段或虛擬機的情況下執行伺服器。 支援: ✅

RateLimit 外掛程式可讓您限制用戶端在指定時間段內可發送的請求數量。

Ktor 提供了幾種設定速率限制的方式:

新增相依性 ​

若要使用 RateLimit,請將 ktor-server-rate-limit 構件新增至您的組建指令碼中:

kotlin
implementation(ktorLibs.server.rateLimit)
上述程式碼片段使用 Ktor 版本目錄 (version catalog) 來指定 Ktor 相依性。
groovy
implementation ktorLibs.server.rateLimit
上述程式碼片段使用 Ktor 版本目錄 (version catalog) 來指定 Ktor 相依性。
xml
<dependency>
    <groupId>io.ktor</groupId>
    <artifactId>ktor-server-rate-limit-jvm</artifactId>
    <version>${ktor_version}</version>
</dependency>

安裝 RateLimit ​

若要將 RateLimit 外掛程式安裝至您的應用程式, 請將其傳遞給指定 模組模組可讓您透過對路由進行分組來建構應用程式。 中的 install 函式。 以下範例示範如何安裝 RateLimit:

  • 在 embeddedServer() 函式呼叫中。
  • 在 Application 類別上明確定義的 module() 擴充函式中。
kotlin
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.plugins.ratelimit.*

fun main() {
    embeddedServer(Netty, port = 8080) {
        install(RateLimit)
        // ...
    }.start(wait = true)
}
kotlin
import io.ktor.server.application.*
import io.ktor.server.plugins.ratelimit.*
// ...
fun Application.module() {
    install(RateLimit)
    // ...
}

設定 RateLimit ​

概覽 ​

Ktor 使用權杖桶(token bucket)演算法進行速率限制,其運作方式如下:

  1. 建立一個具有指定容量的桶子,該容量定義了可用權杖的數量。
  2. 每個傳入的請求都會消耗桶中的一枚權杖:
    • 如果容量足夠,伺服器會處理請求並在回應中包含以下標頭:
      • X-RateLimit-Limit:桶的容量。
      • X-RateLimit-Remaining:桶中剩餘的權杖數量。
      • X-RateLimit-Reset:以秒為單位的 UTC 時間戳記,指定桶重新填滿的時間。
    • 如果容量不足,伺服器會拒絕請求並回傳 429 Too Many Requests 回應。該回應包含 Retry-After 標頭,指示用戶端在發送另一個請求之前應等待多少秒。
  3. 在指定的重新填充週期後,桶會被重新裝滿。

註冊速率限制器 ​

您可以全域套用速率限制至整個應用程式,或是為特定路由註冊速率限制器:

  • 若要全域套用速率限制,請呼叫 global() 函式並設定速率限制器:

    kotlin
    install(RateLimit) {
        global {
            rateLimiter(limit = 5, refillPeriod = 60.seconds)
        }
    }
  • 若要為特定路由設定速率限制,請使用 register() 函式註冊速率限制器:

    kotlin
    install(RateLimit) {
        register {
            rateLimiter(limit = 5, refillPeriod = 60.seconds)
        }
    }

上述範例展示了 RateLimit 外掛程式所需的最低設定。 如果使用 register(),您還需要將註冊的速率限制器套用至特定路由。

設定速率限制 ​

您可以使用以下選項來設定速率限制器。

命名速率限制器 ​

使用 register() 函式為速率限制器指定名稱。接著您可以將具名速率限制器套用至特定路由:

kotlin
    install(RateLimit) {
        register(RateLimitName("protected")) {
            // ...
        }
    }

設定限制與重新填充週期 ​

使用 rateLimiter() 函式設定桶容量與重新填充週期:

  • limit 指定可用權杖的數量。
  • refillPeriod 指定重新裝滿桶的頻率。

以下範例允許每分鐘最多 30 個請求:

kotlin
register(RateLimitName("protected")) {
    rateLimiter(limit = 30, refillPeriod = 60.seconds)
}

依金鑰區分請求 ​

使用 requestKey() 函式為每個請求傳回一個金鑰。具有不同金鑰的請求具有獨立的速率限制。預設情況下,所有請求共享同一個桶。

請確保請求金鑰具有適當的 equals 與 hashCode 實作。

查詢參數 ​

以下範例使用 login 查詢參數來區分使用者:

kotlin
register(RateLimitName("protected")) {
    requestKey { applicationCall ->
        applicationCall.request.queryParameters["login"]!!
    }
}
用戶端 IP 位址 ​

若要為每個用戶端 IP 位址套用獨立的速率限制,請使用 call.request.origin.remoteHost 作為請求金鑰:

kotlin
register(RateLimitName("per-ip")) {
    rateLimiter(limit = 5, refillPeriod = 60.seconds)
    requestKey { call ->
        call.request.origin.remoteHost
    }
}

如果應用程式執行於 Proxy 或負載平衡器後方,請設定 Forwarded headers 外掛程式,以確保 origin.remoteHost 代表原始用戶端位址而非 Proxy。

API 金鑰標頭 ​

若要依據標頭中發送的 API 金鑰進行請求速率限制,請從 requestKey() 傳回該標頭值:

kotlin
register(RateLimitName("per-api-key")) {
    rateLimiter(limit = 5, refillPeriod = 60.seconds)
    requestKey { call ->
        call.request.headers["X-Api-Key"] ?: "anonymous"
    }
}

您也可以將此方法與 API 金鑰驗證結合使用,並使用已驗證的主體 (principal) 代替原始標頭值作為請求金鑰。

存取權杖或 Bearer 權杖 ​

若要為每個 Bearer 權杖套用獨立的速率限制,請從 Authorization 標頭傳回原始權杖作為請求金鑰:

kotlin
requestKey { call ->
    call.request.authorization()?.removePrefix("Bearer ") ?: "anonymous"
}

當請求通過驗證時,建議使用驗證主體作為請求金鑰,為每個已驗證的身分套用獨立的速率限制。

限制已驗證使用者的速率 ​

您可以使用驗證主體作為請求金鑰,按已驗證的使用者套用速率限制。

將 rateLimit() 巢狀置於 authenticate() 內部,然後從 requestKey() 中存取主體:

kotlin
install(Authentication) {
    basic("auth") { validate { UserIdPrincipal(it.name) } }
}
install(RateLimit) {
    register(RateLimitName("per-user")) {
        rateLimiter(limit = 10, refillPeriod = 60.seconds)
        requestKey { call.principal<UserIdPrincipal>()?.name ?: "anonymous" }
    }
}

routing {
    authenticate("auth") {
        rateLimit(RateLimitName("per-user")) {
            get("/api") { call.respondText("OK") }
        }
    }
}

設定請求權重 ​

使用 requestWeight() 函式指定每個請求消耗多少枚權杖。該函式會接收應用程式呼叫 (application call) 與請求金鑰。

在以下範例中,帶有 jetbrains 金鑰的請求消耗一枚權杖,而所有其他請求則消耗兩枚:

kotlin
register(RateLimitName("protected")) {
    requestKey { applicationCall ->
        applicationCall.request.queryParameters["login"]!!
    }
    requestWeight { applicationCall, key ->
        when (key) {
            "jetbrains" -> 1
            else -> 2
        }
    }
}

自訂回應 ​

當套用速率限制時,使用 modifyResponse() 函式自訂回應。

例如,您可以新增自訂的速率限制標頭:

kotlin
register(RateLimitName("protected")) {
    modifyResponse { applicationCall, state ->
        applicationCall.response.header("X-RateLimit-Custom-Header", "Some value")
    }
}

定義速率限制作用域 ​

設定速率限制器後,您可以使用 rateLimit() 函式將其套用至特定路由。

套用預設速率限制器 ​

使用不帶名稱的 rateLimit() 函式套用已註冊的預設速率限制器:

kotlin
routing {
    rateLimit {
        get("/") {
            val requestsLeft = call.response.headers["X-RateLimit-Remaining"]
            call.respondText("Welcome to the home page! $requestsLeft requests left.")
        }
    }
}

套用具名速率限制器 ​

將 RateLimitName 傳遞給 rateLimit() 函式以套用具名速率限制器:

kotlin
routing {
    rateLimit(RateLimitName("protected")) {
        get("/protected-api") {
            val requestsLeft = call.response.headers["X-RateLimit-Remaining"]
            val login = call.request.queryParameters["login"]
            call.respondText("Welcome to protected API, $login! $requestsLeft requests left.")
        }
    }
}

範例 ​

以下範例示範如何將不同的速率限制器套用至不同的路由。 其設定了:

  • 首頁的預設速率限制器。
  • 公開 API 的具名 public 速率限制器。
  • 使用請求金鑰與權重的具名 protected 速率限制器。
  • 分別以用戶端 IP 與 X-Api-Key 標頭為金鑰的具名速率限制器。
  • 用於自訂被拒絕並傳回 429 Too Many Requests 回應之請求的 StatusPages 外掛程式。
kotlin
package com.example

import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.plugins.*
import io.ktor.server.plugins.ratelimit.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlin.time.Duration.Companion.seconds

fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)

fun Application.module() {
    install(RateLimit) {
        register {
            rateLimiter(limit = 5, refillPeriod = 60.seconds)
        }
        register(RateLimitName("public")) {
            rateLimiter(limit = 10, refillPeriod = 60.seconds)
        }
        register(RateLimitName("protected")) {
            rateLimiter(limit = 30, refillPeriod = 60.seconds)
            requestKey { applicationCall ->
                applicationCall.request.queryParameters["login"]!!
            }
            requestWeight { applicationCall, key ->
                when (key) {
                    "jetbrains" -> 1
                    else -> 2
                }
            }
        }
        register(RateLimitName("per-ip")) {
            rateLimiter(limit = 5, refillPeriod = 60.seconds)
            requestKey { call ->
                call.request.origin.remoteHost
            }
        }
        register(RateLimitName("per-api-key")) {
            rateLimiter(limit = 5, refillPeriod = 60.seconds)
            requestKey { call ->
                call.request.headers["X-Api-Key"] ?: "anonymous"
            }
        }
    }
    install(StatusPages) {
        status(HttpStatusCode.TooManyRequests) { call, status ->
            val retryAfter = call.response.headers["Retry-After"]
            call.respondText(text = "429: Too many requests. Wait for $retryAfter seconds.", status = status)
        }
    }
    routing {
        rateLimit {
            get("/") {
                val requestsLeft = call.response.headers["X-RateLimit-Remaining"]
                call.respondText("Welcome to the home page! $requestsLeft requests left.")
            }
        }
        rateLimit(RateLimitName("public")) {
            get("/public-api") {
                val requestsLeft = call.response.headers["X-RateLimit-Remaining"]
                call.respondText("Welcome to public API! $requestsLeft requests left.")
            }
        }
        rateLimit(RateLimitName("protected")) {
            get("/protected-api") {
                val requestsLeft = call.response.headers["X-RateLimit-Remaining"]
                val login = call.request.queryParameters["login"]
                call.respondText("Welcome to protected API, $login! $requestsLeft requests left.")
            }
        }
        rateLimit(RateLimitName("per-ip")) {
            get("/ip-api") {
                val requestsLeft = call.response.headers["X-RateLimit-Remaining"]
                val clientHost = call.request.origin.remoteHost
                call.respondText("Welcome to IP API, $clientHost! $requestsLeft requests left.")
            }
        }
        rateLimit(RateLimitName("per-api-key")) {
            get("/keyed-api") {
                val requestsLeft = call.response.headers["X-RateLimit-Remaining"]
                val apiKey = call.request.headers["X-Api-Key"] ?: "anonymous"
                call.respondText("Welcome to keyed API, $apiKey! $requestsLeft requests left.")
            }
        }
    }
}

如需完整範例,請參閱 rate-limit。