Keep your Express routes, add RDS Postgres, an SNS and SQS queue and a cron job as declarations in the code, and deploy to your own AWS account with git push.

To deploy an Express app with Postgres and a queue to AWS, you need RDS for the database, SQS for the queue, a worker that consumes it, and Fargate or Elastic Beanstalk to run the server, work that often ends up in a Terraform project. Encore is the shortest path: the database, queue and cron job are declared in the app code, and a git push provisions them in your own AWS account. Teams bring their own agents, and Encore provides the environments, the system context and the controls.
The hand-built AWS route works too, and this guide shows both.
The example is a small orders API: POST /orders writes a row and puts a message on a queue, a worker sends the confirmation email, and an hourly job expires unpaid orders.
Verdict. Options 2 to 5 all work, and each adds a second thing to maintain: a Terraform module, a CDK app, a config file or a set of console settings that has to change whenever the app needs a new queue. Encore ranks first because the queue and the database change in the same commit as the route that uses them, and the same code runs on your laptop.
The hand-built path keeps Express as a plain Node process. The quickest AWS-native way to run it is ECS Express Mode: build an image, push it to ECR, and Express Mode creates the Fargate service, an Application Load Balancer with HTTPS and autoscaling. App Runner, which used to fill that role, closed to new customers on April 30, 2026.
eb init -p node.js and eb create give you an Elastic Beanstalk environment of EC2 instances behind a load balancer running npm start. You can add a database from the environment's configuration, but that database is tied to the environment, while an external RDS instance is not deleted when you terminate the environment. Production setups usually launch RDS separately for that reason.
Either way, the database is yours to set up: an RDS for PostgreSQL instance in private subnets, a security group that only accepts port 5432 from the app, and the connection string in Secrets Manager. A minimal Terraform sketch for the data plane looks like this:
resource "aws_db_instance" "shop" {
identifier = "shop"
engine = "postgres"
instance_class = "db.t3.micro"
allocated_storage = 20
db_name = "shop"
username = "shop"
manage_master_user_password = true
# VPC, subnet group, security groups and backups omitted
}
resource "aws_sqs_queue" "order_placed" {
name = "order-placed"
visibility_timeout_seconds = 60
}
resource "aws_secretsmanager_secret" "email_api_key" {
name = "email-api-key"
}
# Set the value out of band before the worker starts, then reference the ARN
# from the task definition secrets block (valueFrom):
# aws secretsmanager put-secret-value --secret-id email-api-key --secret-string "$EMAIL_API_KEY"
resource "aws_iam_role" "shop_task" {
name = "shop-task"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Principal = { Service = "ecs-tasks.amazonaws.com" }
Action = "sts:AssumeRole"
}]
})
}
resource "aws_iam_role_policy" "shop_task" {
name = "shop-task"
role = aws_iam_role.shop_task.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = ["sqs:SendMessage", "sqs:ReceiveMessage", "sqs:DeleteMessage"]
Resource = aws_sqs_queue.order_placed.arn
},
{
Effect = "Allow"
Action = ["secretsmanager:GetSecretValue"]
Resource = aws_secretsmanager_secret.email_api_key.arn
}
]
})
}
The Express route then talks to Postgres over pg and publishes with the AWS SDK:
import crypto from "node:crypto";
import express from "express";
import { Pool } from "pg";
import { SQSClient, SendMessageCommand } from "@aws-sdk/client-sqs";
const app = express();
app.use(express.json());
const db = new Pool({ connectionString: process.env.DATABASE_URL });
const sqs = new SQSClient({});
app.post("/orders", async (req, res) => {
const { email, totalCents } = req.body ?? {};
const publicToken = crypto.randomUUID();
const { rows } = await db.query(
"INSERT INTO orders (public_token, email, total_cents) VALUES ($1, $2, $3) RETURNING id, public_token",
[publicToken, email, totalCents],
);
await sqs.send(
new SendMessageCommand({
QueueUrl: process.env.ORDER_PLACED_QUEUE_URL,
MessageBody: JSON.stringify({ orderId: rows[0].id, email }),
}),
);
res.status(201).json({ id: rows[0].id, publicToken: rows[0].public_token });
});
Publishing after the insert leaves a small gap: if the process stops between the two calls, the order exists without a queue message. Write an outbox row in the same transaction as the order and publish from that table when every order must produce exactly one message, and accept an idempotency key so retries do not create a second order.
A separate worker process (another Fargate service, or the same image with a different command) long-polls the queue with ReceiveMessageCommand and deletes each message only after it has been handled. If the worker crashes first, the message becomes visible again after the visibility timeout and another receive picks it up:
// worker.ts: a second process that drains the order-placed queue.
import {
DeleteMessageCommand,
ReceiveMessageCommand,
SQSClient,
} from "@aws-sdk/client-sqs";
const sqs = new SQSClient({});
const QueueUrl = process.env.ORDER_PLACED_QUEUE_URL!;
async function sendConfirmation(orderId: number, email: string): Promise<void> {
// Call the email provider with Idempotency-Key: order-${orderId}.
console.log("sending confirmation", orderId, email);
}
while (true) {
const { Messages = [] } = await sqs.send(
new ReceiveMessageCommand({ QueueUrl, MaxNumberOfMessages: 10, WaitTimeSeconds: 20 }),
);
for (const m of Messages) {
const { orderId, email } = JSON.parse(m.Body ?? "{}") as { orderId: number; email: string };
await sendConfirmation(orderId, email);
await sqs.send(new DeleteMessageCommand({ QueueUrl, ReceiptHandle: m.ReceiptHandle }));
}
}
Delivery is at least once, so the email call needs an idempotency key, and a redrive policy should move messages that keep failing to a dead-letter queue. BullMQ is the other common answer for a queue in Node, but on AWS it means running Redis on ElastiCache as well.
The hourly cleanup is an EventBridge Scheduler schedule that invokes a Fargate task or a Lambda, with a scheduler execution role that can only invoke the target (for example, ecs:RunTask plus iam:PassRole). The target's own task role and security groups provide access to Postgres; do not reuse the API task role.
Locally you run Postgres and LocalStack or ElasticMQ from Docker Compose, and you keep that compose file in sync with every new queue or migration. Every new queue in the Express code is also a second change in the Terraform or CDK project, and staging only matches production when someone applies the same stack to both.
Encore works alongside your framework and provisions the infrastructure your code declares in your own AWS or GCP account. For Express, the Express migration guide describes the setup used here: mount the existing router on a raw endpoint, then add infrastructure declarations next to it.
Install the CLI first:
Run in your terminal to get started locally.
Then create an empty Encore app, add Express to it and move the router into a service directory:
A service is a directory with an encore.service.ts file:
// shop/encore.service.ts
import { Service } from "encore.dev/service";
export default new Service("shop");
The database is one object, and Encore reads the schema from numbered SQL files in shop/migrations and applies them on deploy:
// shop/db.ts
import { SQLDatabase } from "encore.dev/storage/sqldb";
// Docker Postgres under `encore run`, RDS when deployed to AWS.
export const db = new SQLDatabase("shop", { migrations: "./migrations" });
-- shop/migrations/1_create_orders.up.sql
CREATE TABLE orders (
id BIGSERIAL PRIMARY KEY,
public_token TEXT NOT NULL UNIQUE,
email TEXT NOT NULL,
total_cents INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE sent_emails (
order_id BIGINT PRIMARY KEY REFERENCES orders(id),
status TEXT NOT NULL CHECK (status IN ('pending', 'sent')),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
A Pub/Sub topic is the queue, and on AWS it becomes an SNS topic with an SQS queue for each subscription, including a dead-letter queue:
// shop/events.ts
import { Topic } from "encore.dev/pubsub";
export interface OrderPlaced {
orderId: number;
email: string;
}
// A local broker under `encore run`, SNS with SQS when deployed to AWS.
export const orderPlaced = new Topic<OrderPlaced>("order-placed", {
deliveryGuarantee: "at-least-once",
});
The Express code stays as it is, apart from two setPrototypeOf lines that let Express work with Encore's raw request and response objects, and the /!rest path sends every request to the router:
// shop/app.ts
import crypto from "node:crypto";
import { api, RawRequest, RawResponse } from "encore.dev/api";
import express, { request, response } from "express";
import { db } from "./db";
import { orderPlaced } from "./events";
// Let Express handle Encore's raw request and response objects.
Object.setPrototypeOf(request, RawRequest.prototype);
Object.setPrototypeOf(response, RawResponse.prototype);
const app = express();
app.use(express.json());
app.post("/orders", async (req, res) => {
const { email, totalCents } = req.body ?? {};
if (typeof email !== "string" || !Number.isInteger(totalCents) || totalCents < 0) {
res.status(400).json({ error: "email and a non-negative integer totalCents are required" });
return;
}
const publicToken = crypto.randomUUID();
const order = await db.queryRow<{ id: number; public_token: string }>`
INSERT INTO orders (public_token, email, total_cents)
VALUES (${publicToken}, ${email}, ${totalCents})
RETURNING id, public_token`;
await orderPlaced.publish({ orderId: order!.id, email });
res.status(201).json({ id: order!.id, publicToken: order!.public_token });
});
// Status lookup by unguessable public token, not by sequential id.
app.get("/orders/status/:token", async (req, res) => {
const order = await db.queryRow`
SELECT id, total_cents AS "totalCents", status
FROM orders WHERE public_token = ${req.params.token}`;
if (!order) {
res.status(404).json({ error: "not found" });
return;
}
res.json(order);
});
// Every request goes to the Express router.
export const expressApp = api.raw(
{ expose: true, method: "*", path: "/!rest" },
app,
);
The worker is a subscription in the same service, and delivery is at least once, so the handler claims a pending row in sent_emails (reclaiming only stale pendings after five minutes), calls the provider with an idempotency key derived from the order id, and marks the row sent only after that call returns:
// shop/worker.ts
import { Subscription } from "encore.dev/pubsub";
import log from "encore.dev/log";
import { db } from "./db";
import { orderPlaced } from "./events";
// Delivery is at least once, so the sent_emails row makes a redelivery a no-op.
const _ = new Subscription(orderPlaced, "send-confirmation", {
handler: async ({ orderId, email }) => {
// Claim as pending so concurrent workers cannot both enter the send path.
// Pass orderId as the provider idempotency key so an accepted send is not duplicated.
const claimed = await db.queryRow`
INSERT INTO sent_emails (order_id, status) VALUES (${orderId}, 'pending')
ON CONFLICT (order_id) DO UPDATE
SET updated_at = now()
WHERE sent_emails.status = 'pending'
AND sent_emails.updated_at < now() - interval '5 minutes'
RETURNING order_id, status`;
if (!claimed) {
const existing = await db.queryRow<{ status: string }>`
SELECT status FROM sent_emails WHERE order_id = ${orderId}`;
if (existing?.status === "sent") return;
// Fresh pending claim from another worker: do not ack; retry later.
throw new Error("confirmation send already in progress");
}
if (claimed.status === "sent") return;
log.info("sending confirmation", { orderId, email });
// Call your email provider here with Idempotency-Key: order-${orderId}.
await db.exec`
UPDATE sent_emails SET status = 'sent', updated_at = now()
WHERE order_id = ${orderId}`;
},
});
A cron job calls an Encore endpoint on a schedule. Cron jobs are managed by the Encore platform, with no extra cloud infrastructure in your account. They run only in deployed cloud environments, not locally and not in preview environments, so call the endpoint by hand to test it:
// shop/cleanup.ts
import { api } from "encore.dev/api";
import { CronJob } from "encore.dev/cron";
import { db } from "./db";
export const expirePending = api({}, async (): Promise<void> => {
await db.exec`
UPDATE orders SET status = 'expired'
WHERE status = 'pending' AND created_at < now() - interval '24 hours'`;
});
const _ = new CronJob("expire-pending-orders", {
title: "Expire unpaid orders",
every: "1h",
endpoint: expirePending,
});
encore run starts Postgres in Docker, a local Pub/Sub broker and the app, and applies the migrations. Docker has to be running, and a request to the Express route should come back with the new order id and token:
The local development dashboard at localhost:9400 shows the request, the publish and the subscription handler running. Requests that go through the catch-all endpoint are traced as one raw request, so you see less detail than for typed Encore endpoints until you move routes over.
The same property helps when an AI coding agent works on the app. When the agent adds a second queue, the topic declaration, the subscriber and the route change arrive as one reviewable diff, and the agent can exercise all of it under encore run without AWS credentials on the laptop.
The first deploy creates a VPC across two availability zones, RDS Postgres, the SNS topic and SQS queues, ECR, the load balancer and the service. Instance sizes, Multi-AZ and backups are environment settings in the infrastructure configuration, not code.
Need an API key for the email provider? Declare it with secret("EmailApiKey") and set it with encore secret set --type prod EmailApiKey. On AWS it is stored in Secrets Manager in your account.
ECS Express Mode. The quickest AWS-native way to get the Express container running, with HTTPS and autoscaling from one command. It covers the web service only: RDS, SQS, the worker service, the schedule and the IAM between them are still separate work.
Terraform or AWS CDK. The hand-built section above is the full path: you own the VPC, RDS, SQS, ECS and IAM, and local development is Docker Compose you keep in sync by hand. Both are well documented, and both mean a second program that has to change whenever the Express app needs a new queue or cron job.
Elastic Beanstalk. Beanstalk runs the Express server with little setup, and the Node.js platform runs npm start or a Procfile. The queue, the worker process, IAM and the scheduled job are separate pieces you configure by hand or through .ebextensions.
SST. sst.config.ts with sst.aws.Postgres, sst.aws.Queue and a Service component gets you close in fewer lines, and SST v3 runs on Pulumi. See SST alternatives.
Verdict. If you want your Express app in your own AWS account with Postgres and a queue declared in the app code, add Encore alongside Express. Your routes stay as they are, the database, queue and cron job live in the code that uses them, and the same code runs locally (apart from the cron job, which the Encore platform runs only in deployed cloud environments) and on AWS. Teams bring their own agents, and Encore provides the environments, the system context and the controls, so an agent that adds a second queue can declare the topic and subscriber in the same change and exercise them under encore run. Pick ECS Express Mode when you only need the web service live today, Terraform or AWS CDK if your team already maintains that IaC and wants every resource spelled out, and Elastic Beanstalk only for a small app that will not grow a worker.
To keep Express routes while Postgres and the queue are declared next to them, follow the Express migration guide linked above or the quick start.
Run the Express server as a container on ECS Fargate (ECS Express Mode is the shortest AWS-native route) or on Elastic Beanstalk, create an RDS for PostgreSQL instance in private subnets, store the connection string in Secrets Manager, and allow the app's security group to reach the database on port 5432.
Create an SQS queue, send messages from the Express route with SendMessageCommand from @aws-sdk/client-sqs, and run a separate worker that long-polls with ReceiveMessageCommand and deletes each message after it is handled. The task roles need sqs:SendMessage on the API side and sqs:ReceiveMessage and sqs:DeleteMessage on the worker side.
SQS if you want a managed queue with no servers, IAM-based access and a dead-letter queue. BullMQ if you already run Redis and want job priorities, delays and a dashboard in Node; on AWS that means running ElastiCache or another Redis yourself.
No. You can create the resources in the console, with the EB CLI or with ECS Express Mode. Terraform or CDK usually arrives once staging has to match production, because console settings are hard to repeat.
The Express router is mounted on an Encore raw endpoint, and the database, topic, subscription and cron job are declared in the app code next to the routes. After you connect your AWS account and git push, Encore provisions RDS, SNS with SQS, the Fargate service and the networking in that account. encore run starts Postgres and a local broker on your machine.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.