Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/event-block-compute-docs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@aws-blocks/bb-async-job": patch
"@aws-blocks/bb-cron-job": patch
"@aws-blocks/bb-realtime": patch
"@aws-blocks/blocks": patch
---

Clarify event block compute compatibility and UnsupportedCompute errors: AsyncJob and CronJob support Lambda and container delivery, while Realtime requires default Lambda compute. Distinguish direct Lambda scheduling from the internal AsyncJob queue used by container CronJobs. Align the AsyncJob design and timeout comments with both delivery paths, and document backend-scoped Scheduler permissions for function and queue targets.
48 changes: 25 additions & 23 deletions packages/bb-async-job/DESIGN.md

Large diffs are not rendered by default.

43 changes: 36 additions & 7 deletions packages/bb-async-job/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,11 @@ redelivery counts toward `maxRetries`.

The queue is a standard SQS queue, so delivery is at-least-once and a handler must
already be idempotent to be correct — a message can be delivered more than once
regardless of `batchSize`. Batching widens the window in which that happens: with
regardless of compute type or `batchSize`.

`batchSize` and `maxBatchingWindowSeconds` control the Lambda event-source path,
not the container poller's concurrency. On Lambda, batching widens the window in
which duplicate work happens: with
`batchSize: 10`, a Lambda that times out or runs out of memory partway through a
batch redelivers all ten messages, including the ones whose handler had already
finished. Per-record failures on their own are isolated (only the failed message is
Expand All @@ -116,9 +120,12 @@ latency-sensitive work — a batching window makes SQS wait up to
a user-facing path starts up to that many seconds late. `maxBatchingWindowSeconds: 0`
opts out of the wait while keeping batching.

The queue's visibility timeout is set to the shared Lambda's timeout plus
`maxBatchingWindowSeconds`, because a message's visibility clock starts when the
poller receives it — before the batching window elapses and before the handler runs.
The queue's configured visibility timeout is `900 + maxBatchingWindowSeconds`
seconds, using the framework's default Lambda timeout constant. On the Lambda
path, the batching window consumes part of this visibility period before the
handler runs. On the container path, the poller overrides visibility when receiving
messages and extends it with a heartbeat while each worker runs; the queue setting
is not a container job's execution-time limit.

## Handler Context

Expand All @@ -144,19 +151,42 @@ AsyncJobErrors.ValidationFailed // schema validation failed
AsyncJobErrors.BatchSubmitFailed // one or more messages failed to enqueue
AsyncJobErrors.Timeout // waitUntilComplete() gave up before the job settled
AsyncJobErrors.StatusNotTracked // status method called without trackStatus: true
AsyncJobErrors.UnsupportedCompute // unsupported compute or compute from another backend (synth time)
```

## Compute Compatibility

AsyncJob supports Lambda and container compute:

- **Lambda:** attaches a native SQS event source to the resolved compute's function.
- **Container:** uses an owner-matched SQS poller in the container runtime, with
each delivery dispatched to a worker thread. No Lambda event source is created.

The `compute` option selects a compute explicitly; otherwise the job uses its
scope's resolved compute. Other compute types, and computes from another backend,
Comment thread
xyos marked this conversation as resolved.
Resolved
fail at synth time with `UnsupportedComputeException`.
See [Running on a container compute](#running-on-a-container-compute)
for an example.

## Local Development

In local dev mode, AsyncJob uses an in-process queue. Jobs process via `setTimeout` in the same Node.js process. Retries, DLQ behavior, and payload limits are enforced identically to AWS.

Selecting container compute does not create worker threads locally or enforce
the container delivery timeout. Use a sandbox deployment to exercise those behaviors.

## AWS Deployment

Automatically provisions an SQS queue, dead-letter queue, and connects to the shared API Lambda. Failed jobs become visible for retry after 900 seconds (matching the Lambda timeout).
Automatically provisions an SQS queue and dead-letter queue. Lambda jobs attach
an event source to their resolved Lambda compute; container jobs grant queue
consumption to their compute's task role and are received by its runtime poller.
The container poller deletes a message only after its worker succeeds. On either
path, an unsuccessful delivery becomes available for retry when its visibility
period expires, with SQS redrive moving exhausted messages to the DLQ.

## How Do I Know My Job Ran?

`submit()` is fire-and-forget — it returns as soon as the payload is queued, and the handler runs later in a separate Lambda invocation. Pass `trackStatus: true` and AsyncJob records the job's state for you:
`submit()` is fire-and-forget — it returns as soon as the payload is queued, and the handler runs asynchronously on the job's compute: a Lambda invocation or a container worker thread. Pass `trackStatus: true` and AsyncJob records the job's state for you:

```typescript
const job = new AsyncJob(scope, 'ingest', {
Expand Down Expand Up @@ -236,4 +266,3 @@ handler: async (payload, ctx) => {

**Check the dead-letter queue:** Jobs that fail after `maxRetries` attempts land in the DLQ. In AWS, check the `{scope}-{id}-dlq` queue in the SQS console. In local dev, failed jobs are logged to the console with their full payload.


2 changes: 1 addition & 1 deletion packages/bb-async-job/src/index.aws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ export class AsyncJob<T = unknown> extends Scope {
* `dispatchJobToWorker`). Running each job in its own worker is what makes the
* per-handler wall-clock limit *enforced* rather than cooperative: on timeout
* the parent hard-terminates the worker, so even a pure CPU busy-loop is
* stopped. The limit is the compute's `timeoutSeconds`, stamped as
* stopped. The limit is this job's `timeoutSeconds`, stamped as
* `BLOCKS_HANDLER_TIMEOUT_<id>` at synth.
*
* Concurrency is bounded by `BLOCKS_HANDLER_CONCURRENCY_<id>` (the poller's
Expand Down
9 changes: 5 additions & 4 deletions packages/bb-async-job/src/index.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,12 @@ const MAX_BATCH_PAYLOADS = 10_000;
* **Best practices:**
* - Keep payloads small (< 256 KB) — store large data in FileBucket/KVStore and pass a reference
* - Design handlers to be idempotent — jobs may be delivered more than once
* - Set `visibilityTimeout` to at least 2x the expected handler duration
* - Use `timeoutSeconds` to bound container deliveries; SQS visibility controls redelivery, not code termination
*
* **Scaling (AWS):** SQS standard queues support nearly unlimited throughput.
* By default a dedicated Lambda function processes jobs with automatic
* concurrency scaling. Assign a container `Compute` (via the `compute` option)
* By default the resolved Lambda compute processes jobs with automatic
* concurrency scaling; no dedicated Lambda is created per job. Assign a container
* `Compute` (via the `compute` option)
* to run the handler on Fargate instead — for long-running or high-memory jobs —
* where a self-started poller drains the queue and the service autoscales on
* backlog depth.
Expand Down Expand Up @@ -188,7 +189,7 @@ export class AsyncJob<T = unknown> extends Scope {
*
* The handler runs asynchronously — this method returns immediately with a job ID.
* In local dev, the handler executes via `setTimeout`. In AWS, the payload is
* sent to SQS and a dedicated Lambda processes it.
* sent to SQS and processed on the job's resolved Lambda or container compute.
*
* @param payload - The job data passed to the handler.
* @param options - Optional. `delaySeconds` defers processing (0–900s).
Expand Down
2 changes: 1 addition & 1 deletion packages/bb-async-job/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ export type AsyncJobOptions<T> = AsyncJobBaseOptions<T> &
*
* Assigning a container-backed compute moves delivery from a native SQS
* event source to an owner-matched poller the container self-starts; the
* per-handler wall-clock limit comes from the compute's `timeoutSeconds`. In
* per-handler wall-clock limit comes from this job's `timeoutSeconds`. In
* local dev, compute assignment is transparent — the handler runs in-process.
*/
compute: ComputeProvider<'container'>;
Expand Down
21 changes: 17 additions & 4 deletions packages/bb-cron-job/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,9 +173,22 @@ import { CronJobErrors } from '@aws-blocks/bb-cron-job';

CronJobErrors.InvalidSchedule // schedule expression is not a valid cron or rate format
CronJobErrors.InvalidTimezone // timezone string is not a valid IANA timezone
CronJobErrors.UnsupportedCompute // unsupported compute or compute from another backend (synth time)
```

Both errors are thrown at construction time (fail-fast validation).
`InvalidSchedule` and `InvalidTimezone` are thrown at construction time (fail-fast validation).

## Compute Compatibility

CronJob targets its own `compute`, or inherits its scope's compute:

- **Lambda:** EventBridge Scheduler invokes the resolved compute's function directly.
- **Container:** Scheduler sends each tick to an internal AsyncJob's queue, which
the container drains. See [Running on a container compute](#running-on-a-container-compute).

Other compute types, and computes from another backend, fail at synth time with
`UnsupportedComputeException`. Locally, handlers run in the dev server regardless
of compute selection; this does not reproduce container worker isolation or timeouts.

## Examples

Expand Down Expand Up @@ -280,8 +293,8 @@ In local dev mode, CronJob runs schedules in-process:
Automatically provisions:

- **EventBridge Schedule:** One `AWS::Scheduler::Schedule` per CronJob instance
- **Shared Lambda:** Targets the shared Lambda (same as API handlers and AsyncJob). No dedicated Lambda per job.
- **IAM role:** Per-stack EventBridge Scheduler role with `lambda:InvokeFunction` permission. Its trust policy is limited to schedules in the stack's account and region (`aws:SourceAccount` + `aws:SourceArn` matching `schedule-group/*`).
- **Lambda compute (serverless jobs):** Each schedule targets its resolved function. No dedicated Lambda is created per job.
- **IAM role:** Per-backend EventBridge Scheduler role with access to each job's target: `lambda:InvokeFunction` for Lambda jobs or `sqs:SendMessage` for container jobs. Its trust policy is limited to schedules in the stack's account and region (`aws:SourceAccount` + `aws:SourceArn` matching `schedule-group/*`).
Comment thread
xyos marked this conversation as resolved.
Resolved
- **Schedule name:** Derived from the CronJob's `fullId` (truncated to 64 chars)
- **On a container compute:** The schedule targets an SQS queue and dead-letter queue owned by an internal `AsyncJob` instead of a Lambda function. The scheduler role gets `sqs:SendMessage` on that queue in place of `lambda:InvokeFunction`.

Expand All @@ -294,4 +307,4 @@ CronJob is a **pure infrastructure declaration** — the constructor defines the
| Trigger | Time-based (cron/rate) | Programmatic (`submit()`) |
| Runtime methods | None | `submit()`, `submitBatch()` |
| Use case | Periodic recurring tasks | One-off event-driven work |
| AWS service | EventBridge Scheduler | SQS + Lambda |
| AWS service | EventBridge Scheduler | SQS with Lambda or container compute |
1 change: 1 addition & 0 deletions packages/bb-realtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ import { RealtimeErrors } from '@aws-blocks/bb-realtime';
RealtimeErrors.ValidationFailed // data failed schema validation on publish
RealtimeErrors.PublishFailed // Publish fan-out failed (AWS only)
RealtimeErrors.ConnectionFailed // WebSocket connection or subscribe rejected
RealtimeErrors.UnsupportedCompute // default compute is not Lambda (thrown at synth time)
```

## Best Practices
Expand Down
2 changes: 1 addition & 1 deletion packages/bb-realtime/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@ export const RealtimeErrors = {
PublishFailed: 'PublishFailedException',
ValidationFailed: 'ValidationFailedException',
ConnectionFailed: 'ConnectionFailedException',
/** Thrown at synth time when the resolved compute is not a supported type (only Lambda today). */
/** Thrown at synth time when the default compute is not a supported type (only Lambda today). */
UnsupportedCompute: 'UnsupportedComputeException',
} as const;