Take rental applications with co-applicants, collect income documents into private storage, run tenant screening asynchronously, record every decision against the criteria in force, and send adverse action notices when a report was used.

A rental application is a short form for the applicant and a long process for the property manager. Every adult on the lease applies, pays a fee, uploads proof of income and gets screened. Someone makes a decision, and that decision has legal weight: the Fair Housing Act prohibits discrimination in rental decisions, and the Fair Credit Reporting Act requires a notice when a screening report contributed to a denial or to worse terms.
The backend is where consistency is either enforced or lost. This guide designs the data model and builds the core in TypeScript: applications with co-applicants, private document uploads, asynchronous screening with a verified webhook, decisions tied to a versioned set of criteria, and the adverse action notice.
One application, several applicants. The application belongs to a unit, and each adult is an applicant row with their own fee, documents and screening status. The application is ready for a decision only when every applicant's screening is complete, which is a query rather than a flag someone has to remember to set.
Documents never touch the API. Pay stubs and IDs go straight from the browser to a private bucket through signed upload URLs that expire in minutes. The API records the object key and, when staff need to view a file, issues a short-lived signed download URL. Files are never public, and the API servers never buffer them.
Screening is asynchronous and idempotent. Submitting an application publishes one message per applicant. The consumer calls the screening provider with the applicant ID as the reference, so a retried request maps to the same report. The provider's webhook is verified with an HMAC signature before anything is stored.
Criteria are data. The income-to-rent ratio, the history rules and the documented exceptions are a versioned record. Each decision stores the criteria version and the reasons in structured form. That is what lets you answer "was this applicant treated the same as the last ten" months later.
Adverse action is part of the decision. If the decision is a denial, a conditional approval with a higher deposit, or a required co-signer, and a screening report was a factor, the decision step queues the notice. The CFPB's guidance for renters describes what applicants should receive: the reporting agency's contact details, a statement that the agency did not make the decision, and their right to a free copy of the report and to dispute it.
Screening data has a retention date. Consumer reports and income documents are sensitive and should be deleted once they are no longer needed for the decision or a dispute window. Store a delete_after date per document.
The pieces are an RDS for PostgreSQL database, a private S3 bucket with block public access and a lifecycle rule for retention, an SNS topic and SQS queue with a dead-letter queue for screening requests, Secrets Manager entries for the provider API key and webhook secret, an API service on ECS or Lambda behind a load balancer or API Gateway, and IAM policies that let the API sign S3 URLs, publish to the topic and read only its two secrets. Every one of those also needs a staging copy for testing the provider's sandbox.
Encore is a backend framework with built-in infrastructure. The database, the private bucket, the screening topic and the provider secrets are declared in TypeScript next to the API. encore run starts Postgres, local object storage and an in-memory Pub/Sub, so the whole flow runs on a laptop against the provider's sandbox. A deploy to your own account creates RDS, S3, SNS with SQS and Secrets Manager on AWS, or Cloud SQL, Cloud Storage, Pub/Sub and Secret Manager on GCP. Encore provisions an IAM role for the service, or a service account on GCP. Production secret values are set with encore secret set and are not in the repository, so an AI coding agent working in the code cannot read those. A local override in .secrets.local.cue is readable if it is present.
Run in your terminal to get started locally.
-- applications/migrations/1_applications.up.sql
CREATE TABLE criteria_versions (
id SERIAL PRIMARY KEY,
min_income_ratio NUMERIC NOT NULL, -- e.g. 3.0 = income at least 3x rent
rules JSONB NOT NULL, -- history rules and documented exceptions
effective_from TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE applications (
id TEXT PRIMARY KEY,
unit_id TEXT NOT NULL,
monthly_rent INT NOT NULL,
status TEXT NOT NULL DEFAULT 'open'
CHECK (status IN ('open', 'screening', 'ready', 'decided')),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE applicants (
id TEXT PRIMARY KEY,
application_id TEXT NOT NULL REFERENCES applications (id),
email TEXT NOT NULL,
fee_paid_at TIMESTAMPTZ,
screening_status TEXT NOT NULL DEFAULT 'not_started'
CHECK (screening_status IN ('not_started', 'requested', 'complete', 'failed')),
screening_result JSONB,
agency JSONB -- name, address, phone of the reporting agency
);
CREATE TABLE documents (
object_key TEXT PRIMARY KEY,
applicant_id TEXT NOT NULL REFERENCES applicants (id),
kind TEXT NOT NULL CHECK (kind IN ('id', 'income', 'other')),
delete_after DATE NOT NULL,
uploaded_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Written in the same transaction as the move to screening, published afterwards.
CREATE TABLE screening_outbox (
seq BIGSERIAL PRIMARY KEY,
applicant_id TEXT NOT NULL REFERENCES applicants (id),
claimed_at TIMESTAMPTZ,
claimed_by TEXT
);
CREATE TABLE decisions (
application_id TEXT PRIMARY KEY REFERENCES applications (id),
outcome TEXT NOT NULL CHECK (outcome IN ('approved', 'conditional', 'denied')),
criteria_id INT NOT NULL REFERENCES criteria_versions (id),
reasons JSONB NOT NULL,
report_used BOOLEAN NOT NULL,
decided_by TEXT NOT NULL,
decided_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
The applicant's app asks for an upload URL, then sends the file directly to the bucket. The object key is generated on the server, so applicants cannot overwrite each other's files.
// applications/documents.ts
import { api, APIError } from "encore.dev/api";
import { Bucket } from "encore.dev/storage/objects";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { getAuthData } from "~encore/auth";
import { randomUUID } from "node:crypto";
export const db = new SQLDatabase("applications", { migrations: "./migrations" });
export const docs = new Bucket("applicant-documents", { public: false });
const RETENTION_DAYS = 90;
interface UploadRequest {
applicantId: string;
kind: "id" | "income" | "other";
}
export const createUpload = api(
{ expose: true, auth: true, method: "POST", path: "/applicants/:applicantId/documents" },
async ({ applicantId, kind }: UploadRequest): Promise<{ uploadUrl: string; key: string }> => {
const { userID } = getAuthData()!;
if (userID !== applicantId) {
throw APIError.permissionDenied("not this applicant");
}
const key = `${applicantId}/${kind}/${randomUUID()}`;
await db.exec`
INSERT INTO documents (object_key, applicant_id, kind, delete_after)
VALUES (${key}, ${applicantId}, ${kind}, current_date + ${RETENTION_DAYS}::int)`;
const { url } = await docs.signedUploadUrl(key, { ttl: 600 });
return { uploadUrl: url, key };
},
);
The endpoints are marked auth: true, which requires an auth handler in the app. The handler returns the applicant's ID as userID. createUpload checks that value against the path, and submit checks that the caller is an applicant on that application in the same transaction as the status change. A nightly cron job deletes objects and rows past delete_after, unless the application is under dispute.
Submitting the application writes one outbox row per applicant in the same transaction as the status change, then publishes those rows. A failed publish leaves the rows in place. A cron job every five minutes claims up to 50 pending rows with a unique lease token, publishes them and deletes a row only when that token still matches, so a later run can finish leftover work without one worker removing another worker's rows. Cron jobs are managed by the Encore platform and do not run locally or in preview environments. The subscription calls the provider and is retried with backoff if the provider is down. The webhook is a raw endpoint, which gives access to the exact request body for signature verification.
// applications/screening.ts
import { api, APIError } from "encore.dev/api";
import { Topic, Subscription } from "encore.dev/pubsub";
import { CronJob } from "encore.dev/cron";
import { secret } from "encore.dev/config";
import { getAuthData } from "~encore/auth";
import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
import { db } from "./documents";
const providerKey = secret("ScreeningAPIKey");
const webhookSecret = secret("ScreeningWebhookSecret");
interface ScreeningRequested {
applicantId: string;
}
const screeningRequested = new Topic<ScreeningRequested>("screening-requested", {
deliveryGuarantee: "at-least-once",
});
async function flushScreeningOutbox(applicationId?: string): Promise<void> {
const claim = randomUUID();
const rows: { seq: number; applicant_id: string }[] = [];
const claimed = applicationId
? db.query<{ seq: number; applicant_id: string }>`
UPDATE screening_outbox AS o
SET claimed_at = now(), claimed_by = ${claim}
FROM applicants AS a
WHERE o.seq IN (
SELECT o2.seq FROM screening_outbox o2
JOIN applicants a2 ON a2.id = o2.applicant_id
WHERE a2.application_id = ${applicationId}
AND (o2.claimed_at IS NULL OR o2.claimed_at < now() - interval '5 minutes')
ORDER BY o2.seq
LIMIT 50
)
AND a.id = o.applicant_id
AND (o.claimed_at IS NULL OR o.claimed_at < now() - interval '5 minutes')
RETURNING o.seq, o.applicant_id`
: db.query<{ seq: number; applicant_id: string }>`
UPDATE screening_outbox
SET claimed_at = now(), claimed_by = ${claim}
WHERE seq IN (
SELECT seq FROM screening_outbox
WHERE claimed_at IS NULL OR claimed_at < now() - interval '5 minutes'
ORDER BY seq
LIMIT 50
)
AND (claimed_at IS NULL OR claimed_at < now() - interval '5 minutes')
RETURNING seq, applicant_id`;
for await (const row of claimed) rows.push(row);
rows.sort((a, b) => a.seq - b.seq);
for (const row of rows) {
await screeningRequested.publish({ applicantId: row.applicant_id });
await db.exec`
DELETE FROM screening_outbox WHERE seq = ${row.seq} AND claimed_by = ${claim}`;
}
}
export const relayScreeningOutbox = api({ expose: false }, async (): Promise<void> => {
await flushScreeningOutbox();
});
const _relay = new CronJob("relay-screening-outbox", {
title: "Publish leftover screening outbox rows",
every: "5m",
endpoint: relayScreeningOutbox,
});
export const submit = api(
{ expose: true, auth: true, method: "POST", path: "/applications/:id/submit" },
async ({ id }: { id: string }): Promise<void> => {
const { userID } = getAuthData()!;
await using tx = await db.begin();
const member = await tx.queryRow<{ id: string }>`
SELECT id FROM applicants WHERE application_id = ${id} AND id = ${userID}`;
if (!member) throw APIError.permissionDenied("not an applicant on this application");
const app = await tx.queryRow<{ id: string }>`
UPDATE applications SET status = 'screening'
WHERE id = ${id} AND status = 'open'
AND NOT EXISTS (SELECT 1 FROM applicants WHERE application_id = ${id} AND fee_paid_at IS NULL)
RETURNING id`;
if (app) {
await tx.exec`
INSERT INTO screening_outbox (applicant_id)
SELECT id FROM applicants WHERE application_id = ${id}`;
} else {
const pending = await tx.queryRow<{ seq: number }>`
SELECT o.seq FROM screening_outbox o
JOIN applicants a ON a.id = o.applicant_id
WHERE a.application_id = ${id}
LIMIT 1`;
if (!pending) throw APIError.failedPrecondition("application is not open or fees are unpaid");
}
await tx.commit();
await flushScreeningOutbox(id);
},
);
const _ = new Subscription(screeningRequested, "request-report", {
handler: async ({ applicantId }) => {
// The applicant ID is the provider reference and idempotency key, so a retry maps to the same report.
const res = await fetch("https://screening.example.com/v1/reports", {
method: "POST",
headers: { authorization: `Bearer ${providerKey()}`, "content-type": "application/json" },
body: JSON.stringify({ reference: applicantId }),
signal: AbortSignal.timeout(10_000),
});
if (!res.ok && res.status !== 409) throw new Error(`provider returned ${res.status}`);
await db.exec`
UPDATE applicants SET screening_status = 'requested'
WHERE id = ${applicantId} AND screening_status = 'not_started'`;
},
retryPolicy: { minBackoff: "30s", maxBackoff: "30m", maxRetries: 12 },
});
export const screeningWebhook = api.raw(
{ expose: true, method: "POST", path: "/webhooks/screening" },
async (req, resp) => {
const chunks: Buffer[] = [];
for await (const c of req) chunks.push(c as Buffer);
const body = Buffer.concat(chunks);
const expected = createHmac("sha256", webhookSecret()).update(body).digest();
const given = Buffer.from(String(req.headers["x-signature"] ?? ""), "hex");
if (given.length !== expected.length || !timingSafeEqual(given, expected)) {
resp.writeHead(401).end();
return;
}
const event = JSON.parse(body.toString()) as {
reference: string;
result: unknown;
agency: { name: string; address: string; phone: string };
};
await db.exec`
UPDATE applicants
SET screening_status = 'complete',
screening_result = ${JSON.stringify(event.result)}::jsonb,
agency = ${JSON.stringify(event.agency)}::jsonb
WHERE id = ${event.reference}`;
await db.exec`
UPDATE applications SET status = 'ready'
WHERE status = 'screening'
AND id = (SELECT application_id FROM applicants WHERE id = ${event.reference})
AND NOT EXISTS (
SELECT 1 FROM applicants
WHERE application_id = applications.id AND screening_status <> 'complete')`;
resp.writeHead(204).end();
},
);
The header name and signature format differ by provider. Check your provider's documentation and replace x-signature and the hex encoding to match. The provider URL here is a placeholder.
The decision endpoint reads the current criteria version, stores the outcome, the structured reasons and whether a screening report was a factor, and marks the application decided in the same transaction. When report_used is true and the outcome is denied or conditional, it publishes a notice event. A notice consumer renders the adverse action letter from the stored agency details for each applicant whose report was used and sends it.
Keeping the decision endpoint narrow pays off: it takes an outcome and a list of reason codes from the criteria, not free text, so every decision can be compared with every other one under the same version.
Applications for a unit with one or more applicants, the application fee, identity and income documents, a tenant screening request per applicant, the screening result, and a decision recorded against written criteria. When a screening report contributed to a denial or to worse terms, it also has to produce an adverse action notice.
Screening providers usually work asynchronously. The backend sends a request with an ID of its own, the provider calls a webhook when the report is ready, and the backend verifies the webhook signature, stores the result and moves the application forward. The request is retried from a queue if the provider is unavailable.
Fair housing reviews ask whether every applicant was judged by the same rules. Storing the criteria as a versioned record and saving the version ID on each decision lets you show which income ratio, history rules and exceptions applied to a given applicant on a given day.
Under the Fair Credit Reporting Act, when information in a consumer report, such as a tenant screening report, contributes to denying an application or to worse terms such as a higher deposit or a required co-signer. The notice names the reporting agency and tells the applicant they can get a free copy of the report and dispute it.
With Encore, the applications database, the private document bucket, the screening queue and the webhook secret are declared in TypeScript next to the API. encore run starts them locally, and a deploy creates RDS, S3, SNS with SQS and Secrets Manager in your own AWS account, or the GCP equivalents.
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.