홈으로 돌아가기

ASP.NET Core 속도 제한: 설정 및 알고리즘

ASP.NET Core 속도 제한 설정 가이드. 알고리즘(Fixed Window, Token Bucket), 정책, 큐 및 거부 처리 설명. 프로젝트 통합을 위한 코드 예제.

ASP.NET Core의 속도 제한: 알고리즘 및 정책
Advertisement 728x90

ASP.NET Core에서 속도 제한 설정하기: 개발자를 위한 단계별 가이드

ASP.NET Core의 속도 제한 기능은 서버 부하를 제어하고, DoS 공격으로부터 보호하며, 공정한 자원 분배를 보장합니다. 설정에는 두 단계가 필요합니다: 서비스 등록과 파이프라인에 미들웨어 추가입니다. 모든 종속성은 SDK에 포함되어 있어 추가 패키지가 필요 없습니다.

Program.cs에서 WebApplicationBuilder.ServicesAddRateLimiter를 호출합니다:

builder.Services.AddRateLimiter(options =>
{
    // Konfiguratsiya politik
});

그 다음 미들웨어를 추가합니다:

Google AdInline article slot
app.UseRateLimiter();

이것이 기본 통합입니다. 다음은 알고리즘과 정책에 대한 세부 사항입니다.

알고리즘과 선택적 제한

ASP.NET Core는 여러 속도 제한 알고리즘을 지원합니다:

  • Fixed Window — 고정 시간 창, 간단하지만 부하 급증에 취약합니다.
  • Sliding Window — 슬라이딩 창, 제한을 더 균등하게 분배합니다.
  • Token Bucket — 토큰 버킷, 버스트 트래픽을 허용합니다.
  • Concurrency Limiter — 동시 요청을 제한합니다.

선택성은 제한할 요청을 결정합니다. 전역 제한기는 모든 요청에 적용되며, 선택적 제한기는 키(IP, 사용자 ID)를 사용합니다.

Google AdInline article slot

전역 제한기 예시 (분당 100 요청):

options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(
    httpContext => RateLimitPartition.GetFixedWindowLimiter(
        partitionKey: httpContext.Request.Headers.Host.ToString(),
        factory: partition => new FixedWindowRateLimiterOptions
        {
            AutoReplenishment = true,
            PermitLimit = 100,
            Window = TimeSpan.FromMinutes(1)
        }));
);

그룹화와 제한기 결합

키별 그룹화가 선택성의 기반입니다. AddFixedWindowLimiter 또는 사용자 지정 정책을 사용합니다.

키 그룹화 시나리오:

Google AdInline article slot
  • IP별: partitionKey: httpContext.Connection.RemoteIpAddress?.ToString()
  • 클라이언트별: partitionKey: httpContext.User.Identity?.Name
  • API 엔드포인트별: partitionKey: httpContext.Request.Path
  • 결합 키: IP + User-Agent

AddPolicy를 통해 선택적 제한기를 결합합니다:

options.AddPolicy("ip", httpContext =>
{
    var ip = httpContext.Connection.RemoteIpAddress;
    return new FixedWindowRateLimiterOptions
    {
        PermitLimit = 50,
        Window = TimeSpan.FromMinutes(1),
        QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
        QueueLimit = 10
    };
});

새 기능: 비선택적 제한기 결합—큐가 있는 여러 전역 제한기입니다.

큐와 거부 처리

스파이크를 완화하기 위해 큐를 활성화합니다:

  • QueueLimit — 큐 내 최대값.
  • QueueProcessingOrder — 처리 순서 (OldestFirst / NewestFirst).

거부 작업은 전역 또는 정책별로 설정할 수 있습니다:

options.OnRejected = (context, token) =>
{
    context.HttpContext.Response.StatusCode = 429;
    context.HttpContext.Response.ContentType = "application/json";
    return context.HttpContext.Response.WriteAsync(
        "{"too many requests. try again later.", token);
};

명명된 정책과 익명 정책

명명된 정책은 컨트롤러/작업에 속성을 통해 적용됩니다:

[EnableRateLimiting("policy1")]
public class ApiController : ControllerBase { }

간단한 등록:

options.AddPolicy("policy1", httpContext =>
    new TokenBucketRateLimiterOptions
    {
        TokenLimit = 100,
        QueueLimit = 20,
        ReplenishmentPeriod = TimeSpan.FromMinutes(1),
        TokensPerPeriod = 100,
        AutoReplenishment = true
    });

익명 정책 — 마이크로소프트 문서에 다루지 않은 보너스 기능입니다. 선택기에서 IRateLimiter를 직접 구현합니다.

예시:

options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext>(
    context => new CustomRateLimiter(context));

public class CustomRateLimiter : FixedWindowRateLimiter
{
    // Kastomnaya logic
}

라우트에 연결: [EnableRateLimiting("api")] 또는 [DisableRateLimiting]으로 비활성화합니다.

주요 포인트

  • 속도 제한은 컨트롤러 이전 미들웨어 수준에서 작동합니다.
  • 429 너무 많은 요청을 위해 항상 OnRejected를 구성합니다.
  • 고부하 시나리오에서는 큐를 사용합니다.
  • 세밀한 제어를 위해 정책을 결합합니다 (IP + 엔드포인트).
  • 익명 정책은 표준 API를 넘어 기능을 확장합니다.

— Editorial Team

Advertisement 728x90

다음 읽기