HIGH denial of servicefastapidynamodb

Denial Of Service in Fastapi with Dynamodb

Denial Of Service in Fastapi with Dynamodb — how this specific combination creates or exposes the vulnerability

A Denial of Service (DoS) risk arises in a Fastapi application backed by DynamoDB when unbounded or poorly controlled requests consume downstream capacity, amplify latency, or exhaust local resources. Because DynamoDB has provisioned capacity limits and Fastapi typically runs with a constrained worker/event-loop concurrency model, certain patterns can degrade availability for all clients.

One common scenario: a Fastapi endpoint runs a query or scan without pagination, a tight Limit, or a server-side filter, and the underlying request consumes excessive read capacity units (RCUs). Under heavy load this can cause throttling (HTTP 400-series responses), which Fastapi may propagate as errors or retries, further increasing load. Long-running or unbounded queries also keep async tasks and connection pools occupied, which can lead to thread or event-loop saturation and slow responses for unrelated endpoints.

Authentication and authorization overhead in Fastapi (e.g., many small calls to verify tokens or policies) can compound the issue: if each request triggers multiple DynamoDB calls to validate ownership or permissions, the aggregate RCU consumption grows quickly. In serverless deployments, cold starts combined with bursty traffic can exacerbate tail latency, while missing rate limiting allows a single client to trigger retry storms that amplify consumption.

Because middleBrick scans the unauthenticated attack surface, it can detect missing rate limiting, missing pagination safeguards, missing concurrency controls, and exposed long-running operations that make this combination more susceptible to DoS behavior. Findings include severity-ranked guidance on introducing backpressure, bounding concurrency, and tightening query patterns to reduce resource amplification.

Dynamodb-Specific Remediation in Fastapi — concrete code fixes

Apply bounded, defensive patterns when accessing DynamoDB from Fastapi to reduce amplification and keep resource usage predictable. Use pagination, strict limits, early filtering, timeouts, and concurrency controls to avoid saturating downstream capacity.

Paginated query with Limit and FilterExpression

from typing import List
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
import boto3
from botocore.exceptions import ClientError

app = FastAPI()
dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
table = dynamodb.Table('Items')

class Item(BaseModel):
    id: str
    owner_id: str
    data: str

@app.get("/items", response_model=List[Item])
def list_items(owner_id: str, limit: int = 20):
    if not owner_id or limit <= 0 or limit > 100:
        raise HTTPException(status_code=400, detail="Invalid parameters")
    try:
        response = table.query(
            KeyConditionExpression=boto3.dynamodb.conditions.Key('owner_id').eq(owner_id),
            Limit=limit,
            FilterExpression=boto3.dynamodb.conditions.Attr('deleted').eq(False)
        )
        return response.get('Items', [])
    except ClientError as e:
        raise HTTPException(status_code=502, detail=f"DynamoDB error: {e.response['Error']['Code']}")

Concurrent request guard with asyncio Semaphore

Prevent unbounded concurrency from exhausting connections or throttling DynamoDB.

import asyncio
from fastapi import FastAPI
import boto3

app = FastAPI()
dynamodb = boto3.client('dynamodb', region_name='us-east-1')
semaphore = asyncio.Semaphore(50)  # cap concurrent calls

@app.get("/item/{item_id}")
async def get_item(item_id: str):
    async with semaphore:
        try:
            resp = dynamodb.get_item(
                TableName='Items',
                Key={'id': {'S': item_id}}
            )
            return resp.get('Item', {})
        except Exception as e:
            raise HTTPException(status_code=504, detail="Upstream timeout")

Short timeouts and retries with backoff

Configure timeouts and retry modes to fail fast instead of holding resources.

from botocore.config import Config
import boto3

aws_config = Config(
    connect_timeout=2,
    read_timeout=3,
    retries={
        'max_attempts': 2,
        'mode': 'standard'
    }
)
dynamodb = boto3.resource('dynamodb', config=aws_config, region_name='us-east-1')

Cost and capacity awareness

Prefer queries over scans, project only necessary attributes, and enforce tenant isolation keys to avoid hot partitions. middleBrick’s findings can highlight missing pagination and missing rate limiting that would otherwise amplify DoS risk under load.

Related CWEs: resourceConsumption

CWE IDNameSeverity
CWE-400Uncontrolled Resource Consumption HIGH
CWE-770Allocation of Resources Without Limits MEDIUM
CWE-799Improper Control of Interaction Frequency MEDIUM
CWE-835Infinite Loop HIGH
CWE-1050Excessive Platform Resource Consumption MEDIUM

Frequently Asked Questions

How does middleBrick help identify DoS risks in a Fastapi + DynamoDB setup?
middleBrick scans the unauthenticated attack surface and flags issues such as missing pagination, missing rate limiting, long-running operations, and patterns that can amplify load on DynamoDB, providing severity-ranked findings and remediation guidance.
Can middleBrick fix DoS findings automatically?
middleBrick detects and reports issues with remediation guidance; it does not fix, patch, block, or remediate. Apply the suggested code patterns and controls in your Fastapi service to reduce DoS risk.