Skip to content

Middleware

The middleware base class and the built-in middleware.

Middleware

Base class for FastSQS middleware.

Middleware can hook into message processing before and after handler execution. Subclasses override :meth:before and/or :meth:after.

before async

before(payload: dict, record: dict, context: Any, ctx: 'Context') -> None

Hook called before handler execution.

Parameters:

Name Type Description Default
payload dict

Message payload

required
record dict

SQS record

required
context Any

Lambda context

required
ctx 'Context'

Per-record processing Context

required

Raising from before aborts processing for this record (the handler does not run); already-entered middlewares are still unwound via after.

after async

after(payload: dict, record: dict, context: Any, ctx: 'Context', error: Optional[Exception]) -> None

Hook called after handler execution.

Parameters:

Name Type Description Default
payload dict

Message payload

required
record dict

SQS record

required
context Any

Lambda context

required
ctx 'Context'

Per-record processing Context

required
error Optional[Exception]

Exception if the handler (or a before hook) failed, else None

required

TimingMiddleware

Bases: Middleware

Middleware that measures message processing duration.

Records a start time before processing and stores the duration (ms) in ctx.state after, so downstream middleware/handlers can read it.

before async

before(payload, record, context, ctx)

Record processing start time in ctx.state.

after async

after(payload, record, context, ctx, error)

Compute and store processing duration in ctx.state.

LoggingMiddleware

Bases: Middleware

Middleware that provides structured logging for message processing.

Logs detailed information about message processing including payloads, timing, errors, and processing context with field masking support. Defaults to JSON-line logging on stdout (CloudWatch-friendly), no external dependencies.

log

log(level: str, message: str, **data: Any) -> None

Log a message with structured data.

Parameters:

Name Type Description Default
level str

Log level

required
message str

Log message

required
**data Any

Additional structured data

{}

before async

before(payload, record, context, ctx)

Log message processing start with context information.

after async

after(payload, record, context, ctx, error)

Log message processing completion with results and errors.