Moving Heavy Compute Out of the API: Comparing Async Job Patterns and Measuring AWS Batch on Fargate

Moving Heavy Compute Out of the API: Comparing Async Job Patterns and Measuring AWS Batch on Fargate

How I moved a CPU-heavy calculation out of an API endpoint with AWS Batch array jobs on Fargate and a dependsOn aggregation job. Submission returned in 0.2–0.3 s at any size, while Fargate startup added about one minute.

AWS Authorized Instructor Champion

Moving Heavy Compute Out of the API: Comparing Async Job Patterns and Measuring AWS Batch on Fargate

A Monte Carlo simulation (portfolio loss distribution, VaR/CVaR) inside a FastAPI server held large requests open for more than 20 seconds. This article compares AWS services to move the computation to, and reports measurements from what I built.
  • Compared: four AWS services — AWS Batch, SQS + Lambda, Step Functions, and Lambda durable functions — including what changes now that Lambda's timeout went up to 30 minutes on 2026-11-19
  • Implemented and measured: AWS Batch array jobs with a dependent aggregation job, plus a setup that runs the same computation split across multiple processes on a local PC
  • Short answer: small jobs are faster synchronously or on a process pool. Across the measured range (100k–2M paths), AWS Batch kept the submit response at 0.2–0.3 seconds while handling sizes the synchronous endpoint refuses
Everything below — code, Terraform, and measured numbers — is quoted from a demo project of mine,  available on GitHub .

The API accepts a job and submits an AWS Batch array job on Fargate. Each child job writes its part

Two paths run through this system.
  • Synchronous path (S): the API computes before it responds.
  • Asynchronous path (A): the API submits a job and responds immediately, and AWS Batch does the computing.
The labels S1, S2 and A1–A8 on the diagram's arrows are the step order for each path.

The problem: heavy compute inside the API server

The workload is a Monte Carlo risk calculation. It generates a loss distribution for a portfolio, returning the 99th percentile of losses as VaR99 and the mean of losses beyond VaR99 as CVaR. I picked it as the example because it uses a lot of CPU and memory and splits cleanly into parallel chunks.
The starting point is an API that computes before it responds. It has three problems, which is why it's treated as an anti-pattern in API design.
  • The response is delayed by however long the computation takes. At 100k paths, that was more than 20 seconds.
  • The ALB idle timeout defaults to 60 seconds. A longer computation gets the connection cut, and the computation stays running after the connection is gone.
  • When heavy requests overlap, the computation takes the API's CPU and threads, which also affects response times for other requests.
The code below is the synchronous endpoint after adding the caps described later.
@app.post("/simulate")
def simulate(req: SimulateRequest) -> dict:
if not _sync_slots.acquire(blocking=False):
raise HTTPException(429, "busy: use POST /jobs", headers={"Retry-After": "5"})
try:
t0 = time.perf_counter()
summary = compute.simulate(_params(req), req.method)
finally:
_sync_slots.release()
elapsed_ms = (time.perf_counter() - t0) * 1000
metrics.emit({"SyncDuration": (elapsed_ms, "Milliseconds")}, {"Phase": "sync"}, method=req.method)
return {"summary": summary, "elapsed_ms": round(elapsed_ms)}
The endpoint is a plain  def , not  async def . FastAPI handles  async def  requests one after another on a single thread, called the event loop. With  async def , a CPU-bound computation blocks the event loop and stalls every other request including  /health . With  def , FastAPI runs the request on one of a set of pre-created threads, called the thread pool. The event loop keeps running, but the threads still fight over CPU, and a few heavy requests exhaust the thread pool.
So the synchronous endpoint has hard caps. Concurrency is capped at one computation per API process via  threading.BoundedSemaphore  — excess requests get a 429, though multiple API tasks can each run one. Compute size is capped at  n_paths * n_steps * n_assets <= 500,000,000  — excess requests get a 422. Anything bigger has to run outside the API.

Four AWS services compared as the place to run the compute

Before building, I compared four AWS services as places to move the computation off the API request. I implemented and measured AWS Batch. The other three are not implemented; the comparison is here because it shows why I chose Batch.

A comparison of four AWS services that can run compute outside the API request, and the reason AWS B

Service
Aggregation and dependencies
Per-chunk time limit
Worker startup
How cost accrues
AWS Batch
 dependsOn  starts the aggregation job after every chunk succeeds
No fixed limit; job timeout is optional
About 1 minute for the Fargate task to start (measured)
Billed by task run time, with a 1-minute minimum; zero while idle
SQS + Lambda
You build the completion check and the aggregation yourself
30 minutes, raised from 15 on 2026-11-19
Not measured
Billed by invocations and run time; zero while idle
Step Functions
Runs an aggregation step after the Map state completes
30 minutes for the invoked Lambda
Not measured
State-transition charges plus the invoked Lambda
Lambda durable functions
You write the chunk invocations and the aggregation in the function code; waits and retries are built in
30 minutes for each invoked Lambda; the durable function itself can suspend for up to a year
Not measured
Lambda charges; any durable-functions-specific pricing not checked
I chose AWS Batch because I wanted to verify the idea quickly without building aggregation and state management myself. AWS Batch has both built in: the dependency ("run the aggregation only after every array child succeeds") and per-job state.
I skipped the other three, each for its own reason.
  • SQS + Lambda. Somebody has to know that all chunks finished and then combine them, and that code is mine to write.
  • Step Functions. A Map state would work, and the README itself notes that for short computations and low job counts, calling ECS RunTask from Step Functions is a reasonable alternative to Batch. For this demo, the added Terraform surface and learning cost weren't justified.
  • Lambda durable functions. Built-in orchestration for waits and retries, but fan-out still needs one invocation per chunk. Launched 2025-12; I haven't tried it.

What the 30-minute Lambda timeout changes

On 2026-11-19, AWS raised the timeout for on-demand Lambda functions from 15 to 30 minutes. It covers synchronous, asynchronous, and event source mapping invocations, and SQS triggers are event source mappings. The 30 minutes also applies to Lambda durable functions and to functions invoked from Step Functions Standard workflows. On Lambda Managed Instances, asynchronous and event source mapping invocations have had a 90-minute cap since 2026-09. The announcement lists financial calculations, the same kind of workload as this article, among its use cases.
For this comparison, two things change.
  • SQS + Lambda. Each chunk gets twice the time, so chunks can be larger. The hand-built aggregation is still needed.
  • Step Functions + Lambda. With a Map state invoking Lambda and a reduce step combining the results, Step Functions owns the dependency and the per-job state, and each chunk can run for up to 30 minutes. There's no one-minute Fargate task startup, so for small jobs like the 100k-path run in the measurements, this could reach a result sooner than AWS Batch. I haven't built or measured this setup.

The design: one storage contract, two backends

The computation runs in one of two places: AWS Batch on AWS, or a process pool for local development. Both backends implement the same contract:
  1. The API writes the job input to storage.
  1. The compute layer reads the input, computes, and writes partial results back to storage.
  1. An aggregation step combines the partial results and writes  result.json .
  1. The API decides completion by looking for  result.json . For progress it asks the backend abstraction (DescribeJobs on AWS, the meta file locally) — never the workers themselves.
Because data passes through storage and instructions go through the backend interface, the compute target can be switched between AWS Batch and local without changing API code.  app/backends.py  picks the target from environment variables:
def from_env(store):
queue = os.environ.get("BATCH_JOB_QUEUE")
if queue:
return BatchBackend(store, queue, os.environ["BATCH_JOB_DEFINITION"])
return LocalBackend(store, int(os.environ.get("LOCAL_WORKERS", "0")) or None)
Storage is switched by an environment variable too, just like the compute backend: S3 when  BUCKET  is set, a local directory otherwise.
def from_env():
bucket = os.environ.get("BUCKET")
if bucket:
return S3Storage(bucket)
return LocalStorage(os.environ.get("DATA_DIR", ".data"))
The API endpoints stay thin.  POST /jobs  writes the input and returns 202 immediately;  GET /jobs/{id}  checks  result.json  first and otherwise asks the backend for progress:
@app.post("/jobs", status_code=202)
def submit_job(req: JobRequest) -> dict:
job_id = uuid.uuid4().hex[:12]
params = _params(req)
chunks = min(req.chunks, params.n_blocks) # more chunks than blocks would be meaningless
st.put_json(
store,
st.input_key(job_id),
{"params": params.to_dict(), "method": req.method, "submitted_at": time.time()},
)
backend.submit(job_id, chunks)
return {"job_id": job_id, "chunks": chunks, "status_url": f"/jobs/{job_id}"}

The AWS Batch implementation

Terraform layout

The infrastructure is nine Terraform files; the six that matter here:
File
Contents
 api.tf 
ECS cluster, ALB, API service, autoscaling by request count
 batch.tf 
Fargate Spot-first compute environments, job queue, job definition (retry only on Spot interruption)
 storage.tf 
S3 bucket (objects expire after 7 days), ECR, log groups
 iam.tf 
Task execution role, least-privilege roles for the API and the workers
 monitoring.tf 
Dashboard (API p50/p99, worker duration and memory, job turnaround) and alarms
 network.tf 
Default VPC public subnets and security groups (demo simplification)

Compute environments: Spot first, on-demand fallback

A job queue binds compute environments in priority order. The scheduler first tries to start the task on Fargate Spot, and starts it on regular Fargate if it can't get Spot capacity:
resource "aws_batch_compute_environment" "spot" {
compute_environment_name_prefix = "${var.name}-spot-"
type = "MANAGED"
compute_resources {
type = "FARGATE_SPOT"
max_vcpus = var.batch_max_vcpus
subnets = data.aws_subnets.default.ids
security_group_ids = [aws_security_group.worker.id]
}
lifecycle {
create_before_destroy = true
}
}
resource "aws_batch_compute_environment" "ondemand" {
compute_environment_name_prefix = "${var.name}-od-"
type = "MANAGED"
compute_resources {
type = "FARGATE"
max_vcpus = var.batch_max_vcpus
subnets = data.aws_subnets.default.ids
security_group_ids = [aws_security_group.worker.id]
}
lifecycle {
create_before_destroy = true
}
}
resource "aws_batch_job_queue" "this" {
name = "${var.name}-queue"
state = "ENABLED"
priority = 1
compute_environment_order {
order = 1
compute_environment = aws_batch_compute_environment.spot.arn
}
compute_environment_order {
order = 2
compute_environment = aws_batch_compute_environment.ondemand.arn
}
}
 batch_max_vcpus  is the ceiling on how many worker vCPUs run at once — set on each of the two compute environments, so it's a per-environment cap on parallelism.

Job definition: retry only on Spot interruption

The job definition sets the worker size (default 1 vCPU / 2 GiB, sized from the measured peak memory), points logs at CloudWatch, and — the part worth copying — retries only when Spot kills the task:
resource "aws_batch_job_definition" "worker" {
name = "${var.name}-worker"
type = "container"
platform_capabilities = ["FARGATE"]
container_properties = jsonencode({
image = "${aws_ecr_repository.app.repository_url}:${var.image_tag}"
command = ["python", "-m", "app.worker", "--help"] # overridden at submit time
resourceRequirements = [
{ type = "VCPU", value = tostring(var.worker_vcpu) },
{ type = "MEMORY", value = tostring(var.worker_memory_mib) },
]
environment = [
{ name = "BUCKET", value = aws_s3_bucket.jobs.bucket },
]
executionRoleArn = aws_iam_role.execution.arn
jobRoleArn = aws_iam_role.worker.arn
# default-VPC public subnets: give the task a public IP so it can reach ECR and S3
networkConfiguration = { assignPublicIp = "ENABLED" }
fargatePlatformConfiguration = { platformVersion = "LATEST" }
logConfiguration = {
logDriver = "awslogs"
options = {
"awslogs-group" = aws_cloudwatch_log_group.worker.name
"awslogs-region" = var.region
"awslogs-stream-prefix" = "worker"
}
}
})
# retry only Spot interruptions; do not retry code errors
retry_strategy {
attempts = 3
evaluate_on_exit {
on_status_reason = "Your Spot Task was interrupted*" # Fargate Spot interruption reason
action = "RETRY"
}
evaluate_on_exit {
on_reason = "*"
action = "EXIT"
}
}
timeout {
attempt_duration_seconds = 1800
}
}
 evaluate_on_exit  matches the status reason of a Fargate Spot interruption and allows up to three attempts in total; any other failure exits immediately. A job that fails from a code bug fails the same way on every retry, and it takes three times as long to find out.

Submitting an array job plus a dependent reduce job

 BatchBackend.submit  calls  submit_job  twice to submit two jobs:
  • Array job: AWS Batch starts  size  copies of the same container. Each container receives the number of the chunk it handles in the environment variable  AWS_BATCH_JOB_ARRAY_INDEX .
  • Aggregation job: its  dependsOn  points at the array job, so it starts only after every chunk job succeeds.
def submit(self, job_id: str, n_chunks: int) -> dict:
base = ["python", "-m", "app.worker"]
args = ["--job-id", job_id, "--chunks", str(n_chunks)]
chunk = {
"jobName": f"chunk-{job_id}",
"jobQueue": self.queue,
"jobDefinition": self.definition,
"containerOverrides": {"command": [*base, "chunk", *args]},
}
if n_chunks > 1: # array jobs require size >= 2
chunk["arrayProperties"] = {"size": n_chunks}
chunk_job = self.batch.submit_job(**chunk)["jobId"]
reduce_job = self.batch.submit_job(
jobName=f"reduce-{job_id}",
jobQueue=self.queue,
jobDefinition=self.definition,
dependsOn=[{"jobId": chunk_job}], # runs only after every array element succeeds
containerOverrides={"command": [*base, "reduce", *args]},
)["jobId"]
meta = {"backend": "batch", "chunk_job": chunk_job, "reduce_job": reduce_job, "n_chunks": n_chunks}
st.put_json(self.store, st.meta_key(job_id), meta)
return meta
Note:  arrayProperties.size  must be at least 2, so  n_chunks == 1  submits a plain job instead.
Note: the array job as a whole stays  PENDING  while the chunk jobs run. Check progress by counting the chunk jobs in each state;  statusSummary  in the code below holds those counts.
summary = chunk.get("arrayProperties", {}).get("statusSummary")
if summary is None: # chunks=1 means no array — count the single job status as-is
summary = {chunk.get("status", "SUBMITTED"): 1}

S3 key layout

Everything for one job lives under one prefix, and the bucket lifecycle rule deletes  jobs/  objects after 7 days:
def input_key(job_id: str) -> str:
return f"jobs/{job_id}/input.json"
def part_key(job_id: str, index: int) -> str:
return f"jobs/{job_id}/parts/{index:04d}.npy"
def result_key(job_id: str) -> str:
return f"jobs/{job_id}/result.json"
def meta_key(job_id: str) -> str:
return f"jobs/{job_id}/meta.json"
The four S3 files:
  •  input.json : the job input the API creates
  •  parts/NNNN.npy : each chunk job's result, a NumPy array of loss values
  •  result.json : the aggregated result;  GET /jobs/{id}  decides completion by whether this file exists
  •  meta.json : the AWS Batch job IDs and chunk count
The workers never call the API. Data passes between the API and the workers through S3, and job control goes through the AWS Batch API.

The worker entry point

The same container image serves the API, the chunk workers, and the reduce job — only the command differs. The worker is a small CLI:
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("phase", choices=["chunk", "reduce"])
ap.add_argument("--job-id", required=True)
ap.add_argument("--chunks", type=int, required=True)
ap.add_argument("--index", type=int, default=0)
a = ap.parse_args()
store = st.from_env()
if a.phase == "chunk":
# Batch array jobs pass the element index through this env var
index = int(os.environ.get("AWS_BATCH_JOB_ARRAY_INDEX", a.index))
run_chunk(store, a.job_id, index, a.chunks)
else:
run_reduce(store, a.job_id, a.chunks)
A chunk worker reads the input, computes its slice of blocks, writes  parts/NNNN.npy , and emits metrics. The reduce job concatenates all parts, computes VaR/CVaR, and writes  result.json  with  submitted_at  and  finished_at  so turnaround is measurable end to end.

Splitting without changing the result

Parallelizing a Monte Carlo simulation raises a fair question: does the split change the numbers? I made randomness deterministic per block — paths are grouped into blocks of 5,000, and block  b  seeds its RNG with  [seed, b] :
def block_vectorized(p: Params, b: int) -> np.ndarray:
"""Tuned implementation: computes sub_batch(p) paths at a time with NumPy."""
mu, sigma, w = market(p)
rng = np.random.default_rng([p.seed, b])
n = _block_paths(p, b)
losses = np.empty(n)
size = sub_batch(p)
for start in range(0, n, size):
m = min(size, n - start)
z = rng.standard_normal((m, p.n_steps, p.n_assets))
z *= sigma
z += 1.0 + mu
growth = z.prod(axis=1)
losses[start : start + m] = 1.0 - growth @ w
return losses
Whichever worker computes block  b , it produces identical losses — so the result is independent of the chunk count. The 100k-path runs below confirm it: VaR99 came out  0.1256448805378465  for  /simulate , 4 chunks, and 8 chunks alike.
Memory use is bounded by  SUB_BATCH_BYTES : instead of fixing a sub-batch by path count, the code caps the bytes of random numbers expanded at once. Inputs with more days or assets automatically shrink the sub-batch, which is what keeps worker memory bounded — and the measured peak is what set the 2 GiB job-definition limit.

Registering CloudWatch metrics from logs

When a worker prints one JSON line in CloudWatch's Embedded Metric Format (EMF) to stdout, the metric is registered in CloudWatch. No  PutMetricData  permission or SDK call is needed:
def emit(metrics: dict[str, tuple[float, str]], dimensions: dict[str, str], **properties) -> None:
"""metrics is {name: (value, unit)}; units are Milliseconds, Megabytes, Count, etc."""
record = {
"_aws": {
"Timestamp": int(time.time() * 1000),
"CloudWatchMetrics": [
{
"Namespace": NAMESPACE,
"Dimensions": [list(dimensions)],
"Metrics": [{"Name": k, "Unit": unit} for k, (_, unit) in metrics.items()],
}
],
},
**dimensions,
**{k: v for k, (v, _) in metrics.items()},
**properties,
}
print(json.dumps(record), file=sys.stdout, flush=True)
# (bookkeeping for the local metrics page omitted)
Chunk workers emit  ChunkDuration ,  PeakMemory , and  Paths ; the reduce job emits  ReduceDuration  and  JobTurnaround .  monitoring.tf  builds a dashboard from these plus ALB  TargetResponseTime  and ECS  CPUUtilization , and an alarm enters ALARM state when  PeakMemory  exceeds 80% of the job definition's memory limit (no notification is wired — it's a sizing signal on the dashboard). Note that  PeakMemory  is emitted after a successful run, so a job that dies of OOM never reports it.

IAM: without s3:ListBucket you get 403

Each role is least-privilege: the worker can only read and write  jobs/* ; the API additionally gets  batch:SubmitJob  on the specific queue and job definition, plus  DescribeJobs  and  GetMetricData  (neither supports resource-level scoping). The subtle statement is  s3:ListBucket :
data "aws_iam_policy_document" "api" {
statement {
actions = ["s3:GetObject", "s3:PutObject"]
resources = ["${aws_s3_bucket.jobs.arn}/jobs/*"]
}
# needed to check that no result exists yet. without it, S3 returns 403 (not 404)
# for missing objects, and GET /jobs/{id} 500s for the whole run.
# HeadObject can't be conditioned on s3:prefix, so no prefix scoping; the bucket is jobs-only.
statement {
actions = ["s3:ListBucket"]
resources = [aws_s3_bucket.jobs.arn]
}
...
}
 GET /jobs/{id}  calls  head_object  to check whether  result.json  exists yet. Without  s3:ListBucket  on the bucket, S3 returns 403 instead of 404 for a missing key — so every poll on a running job returned a 500, and I added  s3:ListBucket . Because  HeadObject  permissions can't be scoped by prefix, the bucket is dedicated to jobs.

The local backend for development

 LocalBackend  runs the same contract with a  ProcessPoolExecutor  and a directory. A background thread submits chunk callables, waits on the futures, then calls  run_reduce  — the same  run_chunk / run_reduce  functions the Batch containers run. It uses the  spawn  context because the API process holds threads:
class LocalBackend:
def __init__(self, store: st.LocalStorage, max_workers: int | None = None):
self.store = store
# the API holds threads, so spawn (not fork) the worker processes
self.pool = ProcessPoolExecutor(max_workers=max_workers, mp_context=multiprocessing.get_context("spawn"))
def submit(self, job_id: str, n_chunks: int) -> dict:
st.put_json(self.store, st.meta_key(job_id), {"backend": "local", "status": "RUNNING", "n_chunks": n_chunks})
threading.Thread(target=self._run, args=(job_id, n_chunks), daemon=True).start()
return {"backend": "local"}
The payoff of the shared contract: local development exercises the exact same submit → chunk → reduce →  result.json  flow as the AWS version, with no AWS account involved. Switching backends is configuration ( BUCKET ,  BATCH_JOB_QUEUE ,  BATCH_JOB_DEFINITION ), not a code change.
A local run looks like this (the full project is on GitHub). The reference container uses Python 3.12, and  app/metrics.py  reads the  resource  module, so a Linux-like environment is assumed.
pip install -r requirements.txt pytest httpx
uvicorn app.api:app --port 8000
# in another terminal, while uvicorn runs
curl -s -X POST localhost:8000/jobs -H 'content-type: application/json' -d '{"n_paths":100000,"chunks":4}'
# returns {"job_id":"…","chunks":4,"status_url":"/jobs/…"}
# check the result with the returned job_id (wait until it is SUCCEEDED)
curl -s localhost:8000/jobs/<job_id>
On AWS, the deploy is Terraform in two passes, and assumes the AWS CLI and Terraform are set up — create the ECR repository first, build and push the image, then  terraform apply  for the rest. Tearing it down is  terraform destroy  — the S3 bucket has  force_destroy  and the ECR repo  force_delete , so contents are deleted too.

Measurements

All AWS numbers are from a single run date (2026-11-08) in ap-northeast-1, with a 0.5-vCPU API task and 1-vCPU/2-GiB workers on Fargate. Every simulation is 250 days × 20 assets; only path count and chunk count vary.
Method
Paths
Parallelism
Submit response
Time to result
 POST /simulate 
20k
1
waits for the computation
4.6 s
 POST /simulate 
100k
1
waits for the computation
20.3 s
 POST /jobs 
100k
4 / 8
202 in 0.2–0.3 s
80 s
 POST /jobs 
1M
8
202 in 0.2–0.3 s
98 s
 POST /jobs 
2M
16
202 in 0.2–0.3 s
92 s
Three things stand out:
  • For 100k paths,  /jobs  is slower than  /simulate  (80 s vs 20.3 s). The dominant cost is Fargate task startup — roughly a minute before the first chunk worker computes anything.
  • At 1M+ paths  /simulate  refuses the request entirely (over the 500M work cap), while  /jobs  scales: 20× the paths for roughly the same turnaround (80 s → 92 s). Each configuration was measured once, so treat these as single observations.
  • VaR99 for 100k paths was identical across  /simulate , 4 chunks, and 8 chunks:  0.1256448805378465 .
For the local backend (4-core environment, 100k paths):
Method
Time
Result
 POST /simulate  (inside the API)
8.7 s
VaR99 = 0.125645
 POST /jobs  (4 workers)
instant submit, 2.8 s to result
VaR99 = 0.125645 (identical)
And the micro-benchmark that motivated the vectorized implementation (20k paths, 4-core environment, each variant in a separate process):
Implementation
Workers
Time (s)
Speedup
Peak memory (MB)
naive (pandas, one path at a time)
1
3.38
1.0x
76
vectorized (NumPy, ~1,000 paths at a time)
1
1.77
1.9x
151
vectorized
2
1.08
3.1x
134
vectorized
4
0.59
5.7x
134
A cProfile run on the naive implementation put about 60% of its time in pandas  +  and  prod ; vectorizing roughly doubled the speed, and the rest is random-number generation, which parallel execution reduced further in this benchmark. The peak-memory column is the larger of the parent/child RSS — not a sum across workers.

What the numbers say

Going async pays off for jobs whose computation takes longer than the roughly one minute a Fargate task needs to start.
  • Small jobs: at 100k paths, synchronous  /simulate  took 20.3 s and AWS Batch took 80 s, so synchronous was faster. Most of the 80 s was the one-minute task startup.
  • Large jobs: 1M paths finished in 98 s and 2M paths in 92 s. Doubling the paths didn't change the time much, because the chunk count went from 8 to 16 and the chunks ran in parallel.
  • API load: on the async path the API doesn't compute, so a small 0.5-vCPU task is enough.

What I learned

  • Deterministic splitting is a feature, not a detail. Seeding per block makes the result independent of chunk count, which made every measurement trustworthy and the test trivial ( tests/test_compute.py  asserts equality across chunk counts).
  • Separate the API from the compute layer through storage, not RPC. Because the API only looks for  result.json , swapping a process pool for AWS Batch changed one file ( backends.py ) and zero endpoints. ECS RunTask would slot into the same shape.
  • Retry only infrastructure failures. Matching  on_status_reason = "Your Spot Task was interrupted*"  ends jobs that fail the same way every time, such as code bugs, without retrying them.
  • Registering metrics through logs removes a permission and an SDK call. Printing one JSON line produces  ChunkDuration ,  PeakMemory , and  JobTurnaround  in CloudWatch with no  cloudwatch:PutMetricData  in the worker role — which is also why the worker role is a single S3 statement.
  • Budget for the 403-not-404 S3 trap early. Missing  s3:ListBucket  turned every "still running" poll into a 500.
  • CPU work belongs in  def  endpoints, with a semaphore anyway.  async def  would freeze the event loop;  def  alone would still let heavy requests exhaust the thread pool.

What I haven't verified

Item
What isn't verified
Switching to regular Fargate
Whether any measured job started on the regular Fargate environment, and how much time the switch adds
Retry after a Spot interruption
Whether the  evaluate_on_exit  retry works on a real Spot interruption
Placement between compute environments
How AWS Batch places jobs between the two compute environments; the documentation doesn't describe it in detail
ECS console display
Whether creating a Fargate compute environment shows a cluster in the ECS console
Jobs beyond the measured range
Behavior above 2M paths and 16 chunks; the API accepts up to 5M paths and 1,000 chunks

Production gaps (deliberately out of scope)

This is a demo, so a few things are intentionally simple:
  • Private subnets and VPC endpoints (S3, ECR, CloudWatch Logs) instead of public subnets.
  • Terraform state in S3 (noted as a comment in  versions.tf ).
  • Job state in DynamoDB for per-tenant history and billing.
  • HTTPS and authentication on the ALB.
  • For short computations at low job volume, Step Functions calling ECS RunTask directly is a reasonable alternative to Batch. With the 30-minute Lambda timeout, Step Functions invoking Lambda is now a candidate too (see the comparison section).

Wrap-up

  • Move computation that takes tens of seconds out of the API, and limit the API to accepting job submissions.
  • AWS Batch array jobs plus a  dependsOn  aggregation job give you parallel computation without building aggregation and state management yourself.
  • The submit response stayed at 0.2–0.3 seconds for both 100k and 2M paths.
  • On the async path, Fargate task startup takes about a minute. Jobs that compute in under a minute finish sooner synchronously.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article