How to generate an amortization schedule in cents, collect each installment by ACH debit with an idempotency key, handle returns that arrive after settlement, retry insufficient funds within the Nacha limits, and run it on AWS or GCP.

A lending product can launch with a list of due dates and a script that charges borrowers, and it breaks the first time an ACH debit comes back for insufficient funds two days after it looked settled. The installment then has to reopen, within Nacha retry limits.
This guide builds a repayment service with an amortization schedule in cents, one attempt row per presentment, a return webhook and capped retries.
Nacha allows a debit returned for insufficient or uncollected funds to be reinitiated a maximum of two times, within 180 days of the original settlement date, and treats changes to the amount or company name made to disguise a retry as a violation, as its operations bulletin on questionable debits describes. That makes the attempt history a compliance record as well as a log, which is why each presentment is its own row.
The schedule is computed once at origination and written in one statement with unnest over arrays of dates and amounts. A daily job inserts the next attempt for every installment that is due, has no open or settled attempt and has fewer than three presentments, using INSERT ... SELECT ... ON CONFLICT DO NOTHING so a second run in the same day inserts nothing. Each attempt then has to reach the processor through a queue with retries, the processor's settlement and return events need an endpoint that applies them in a transaction, and the whole flow needs a Postgres that behaves the same on a laptop as in production, since the guarantees live in unique constraints and ON CONFLICT.
Encore brings infrastructure from code, so the loan tables, the collection topic and the daily autopay job are declared with the endpoints and created in your own AWS or GCP account on deploy, which keeps borrower data and bank details in an account you control. The AWS docs list Fargate, RDS and SNS with SQS, and Pave Bank built a bank in 9 months with Encore Platform, as its case study describes.

Run in your terminal to get started locally.
The service writes the schedule at origination, creates attempts from a daily job and submits each one from a subscriber with the attempt ID as the idempotency key. Settlement and return events from the processor arrive at one endpoint, and a return reopens the installment for a retry only when the code allows it:
// repayments/repayments.go
package repayments
import (
"context"
"errors"
"fmt"
"math"
"time"
"encore.dev/beta/errs"
"encore.dev/cron"
"encore.dev/pubsub"
"encore.dev/rlog"
"encore.dev/storage/sqldb"
)
var db = sqldb.NewDatabase("repayments", sqldb.DatabaseConfig{Migrations: "./migrations"})
type CreateLoanParams struct {
BorrowerID int64 `json:"borrower_id"`
PrincipalCents int64 `json:"principal_cents"`
AprBps int64 `json:"apr_bps"` // 1299 means 12.99%
Months int `json:"months"`
FirstDue string `json:"first_due"` // YYYY-MM-DD
}
type Loan struct {
ID int64 `json:"id"`
PaymentCents int64 `json:"payment_cents"`
Installments int `json:"installments"`
TotalInterest int64 `json:"total_interest_cents"`
}
//encore:api public method=POST path=/loans
func CreateLoan(ctx context.Context, p *CreateLoanParams) (*Loan, error) {
if p.PrincipalCents <= 0 || p.AprBps < 0 || p.Months < 1 || p.Months > 360 {
return nil, &errs.Error{Code: errs.InvalidArgument, Message: "invalid principal, rate or term"}
}
first, err := time.Parse("2006-01-02", p.FirstDue)
if err != nil {
return nil, &errs.Error{Code: errs.InvalidArgument, Message: "first_due must be YYYY-MM-DD"}
}
r := float64(p.AprBps) / 10000 / 12
payment := int64(math.Ceil(float64(p.PrincipalCents) / float64(p.Months)))
if r > 0 {
payment = int64(math.Round(float64(p.PrincipalCents) * r / (1 - math.Pow(1+r, -float64(p.Months)))))
}
balance := p.PrincipalCents
var seqs []int32
var dues []time.Time
var principal, interest []int64
loan := &Loan{Installments: p.Months, PaymentCents: payment}
for i := 1; i <= p.Months; i++ {
in := int64(math.Round(float64(balance) * r))
pr := min(payment-in, balance)
if i == p.Months {
pr = balance // the last installment clears what is left
}
balance -= pr
seqs = append(seqs, int32(i))
dues = append(dues, first.AddDate(0, i-1, 0))
principal = append(principal, pr)
interest = append(interest, in)
loan.TotalInterest += in
}
tx, err := db.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
err = tx.QueryRow(ctx, `
INSERT INTO loans (borrower_id, principal_cents, apr_bps)
VALUES ($1, $2, $3) RETURNING id`, p.BorrowerID, p.PrincipalCents, p.AprBps).Scan(&loan.ID)
if err != nil {
return nil, err
}
_, err = tx.Exec(ctx, `
INSERT INTO installments (loan_id, seq, due_on, principal_cents, interest_cents)
SELECT $1, s, d, pr, i
FROM unnest($2::int[], $3::date[], $4::bigint[], $5::bigint[]) AS u(s, d, pr, i)`,
loan.ID, seqs, dues, principal, interest)
if err != nil {
return nil, err
}
return loan, tx.Commit()
}
type AttemptCreated struct {
AttemptID int64 `json:"attempt_id"`
}
var attempts = pubsub.NewTopic[*AttemptCreated]("collection-attempt-created", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
//encore:api private
func CreateAttempts(ctx context.Context) error {
rows, err := db.Query(ctx, `
INSERT INTO attempts (loan_id, seq, attempt_no, amount_cents)
SELECT i.loan_id, i.seq, count(a.id) + 1, i.principal_cents + i.interest_cents
FROM installments i
JOIN loans l ON l.id = i.loan_id AND l.autopay
LEFT JOIN attempts a ON a.loan_id = i.loan_id AND a.seq = i.seq
WHERE i.status = 'due' AND i.due_on <= current_date
GROUP BY i.loan_id, i.seq, i.principal_cents, i.interest_cents
HAVING count(a.id) FILTER (WHERE a.status <> 'returned') = 0 AND count(a.id) < 3
ON CONFLICT (loan_id, seq, attempt_no) DO NOTHING
RETURNING id`)
if err != nil {
return err
}
var ids []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
rows.Close()
return err
}
ids = append(ids, id)
}
rows.Close()
if err := rows.Err(); err != nil {
return err
}
for _, id := range ids {
if _, err := attempts.Publish(ctx, &AttemptCreated{AttemptID: id}); err != nil {
return err
}
}
return nil
}
var _ = cron.NewJob("autopay-collections", cron.JobConfig{
Title: "Create autopay attempts for due installments",
Schedule: "0 6 * * 1-5",
Endpoint: CreateAttempts,
})
// submitDebit stands in for your processor's API. It must treat the key as an
// idempotency key, so the same attempt never creates two debits.
func submitDebit(ctx context.Context, key string, loanID, cents int64) error {
rlog.Info("submitting ACH debit", "key", key, "loan", loanID, "cents", cents)
return nil
}
var _ = pubsub.NewSubscription(attempts, "submit-debit", pubsub.SubscriptionConfig[*AttemptCreated]{
Handler: func(ctx context.Context, m *AttemptCreated) error {
var loanID, cents int64
err := db.QueryRow(ctx, `
SELECT loan_id, amount_cents FROM attempts
WHERE id = $1 AND status = 'pending'`, m.AttemptID).Scan(&loanID, ¢s)
if errors.Is(err, sqldb.ErrNoRows) {
return nil // already submitted
}
if err != nil {
return err
}
if err := submitDebit(ctx, fmt.Sprintf("attempt-%d", m.AttemptID), loanID, cents); err != nil {
return err
}
_, err = db.Exec(ctx, `
UPDATE attempts SET status = 'submitted', submitted_at = now()
WHERE id = $1 AND status = 'pending'`, m.AttemptID)
return err
},
RetryPolicy: &pubsub.RetryPolicy{MinBackoff: time.Minute, MaxBackoff: time.Hour, MaxRetries: 10},
})
type DebitEvent struct {
AttemptID int64 `json:"attempt_id"`
Outcome string `json:"outcome"` // "settled" or "returned"
ReturnCode string `json:"return_code"` // for example R01
}
// DebitEvents receives settlement and return events from the processor.
//
//encore:api public method=POST path=/ach/events
func DebitEvents(ctx context.Context, e *DebitEvent) error {
tx, err := db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback()
var loanID, seq, attemptNo int64
switch e.Outcome {
case "settled":
err = tx.QueryRow(ctx, `
UPDATE attempts SET status = 'settled', settled_at = now()
WHERE id = $1 AND status = 'submitted'
RETURNING loan_id, seq, attempt_no`, e.AttemptID).Scan(&loanID, &seq, &attemptNo)
if errors.Is(err, sqldb.ErrNoRows) {
return nil // duplicate or late event
}
if err != nil {
return err
}
_, err = tx.Exec(ctx, `
UPDATE installments SET status = 'paid'
WHERE loan_id = $1 AND seq = $2 AND status = 'due'`, loanID, seq)
case "returned":
err = tx.QueryRow(ctx, `
UPDATE attempts SET status = 'returned', return_code = $2, returned_at = now()
WHERE id = $1 AND status IN ('submitted', 'settled')
RETURNING loan_id, seq, attempt_no`, e.AttemptID, e.ReturnCode).Scan(&loanID, &seq, &attemptNo)
if errors.Is(err, sqldb.ErrNoRows) {
return nil
}
if err != nil {
return err
}
retryable := (e.ReturnCode == "R01" || e.ReturnCode == "R09") && attemptNo < 3
next := "servicing"
if retryable {
next = "due"
}
_, err = tx.Exec(ctx, `
UPDATE installments SET status = $3
WHERE loan_id = $1 AND seq = $2`, loanID, seq, next)
default:
return &errs.Error{Code: errs.InvalidArgument, Message: "outcome must be settled or returned"}
}
if err != nil {
return err
}
return tx.Commit()
}
-- repayments/migrations/1_create_tables.up.sql
CREATE TABLE loans (
id BIGSERIAL PRIMARY KEY,
borrower_id BIGINT NOT NULL,
principal_cents BIGINT NOT NULL CHECK (principal_cents > 0),
apr_bps BIGINT NOT NULL CHECK (apr_bps >= 0),
autopay BOOLEAN NOT NULL DEFAULT true,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE installments (
loan_id BIGINT NOT NULL REFERENCES loans (id),
seq INT NOT NULL,
due_on DATE NOT NULL,
principal_cents BIGINT NOT NULL CHECK (principal_cents >= 0),
interest_cents BIGINT NOT NULL CHECK (interest_cents >= 0),
status TEXT NOT NULL DEFAULT 'due' CHECK (status IN ('due', 'paid', 'servicing')),
PRIMARY KEY (loan_id, seq)
);
CREATE TABLE attempts (
id BIGSERIAL PRIMARY KEY,
loan_id BIGINT NOT NULL,
seq INT NOT NULL,
attempt_no INT NOT NULL CHECK (attempt_no BETWEEN 1 AND 3),
amount_cents BIGINT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'submitted', 'settled', 'returned')),
return_code TEXT,
submitted_at TIMESTAMPTZ,
settled_at TIMESTAMPTZ,
returned_at TIMESTAMPTZ,
UNIQUE (loan_id, seq, attempt_no),
FOREIGN KEY (loan_id, seq) REFERENCES installments (loan_id, seq)
);
encore run starts Postgres locally and applies the migration. A loan can be created with curl, the schedule inspected with encore db shell repayments, and the attempt job and the return endpoint called by hand. Cron jobs do not run locally, so the autopay job is tested by calling CreateAttempts from the local development dashboard, then posting an R01 return and calling it again, which inserts the second presentment if the return code allows a retry. The database docs cover transactions, the Pub/Sub docs cover retries and dead-letter queues, and the cron docs cover schedules, which the Encore platform manages.
Deploying follows Connect your cloud account and a push, and the database, the topic and the schedule are created in your account. An AI coding agent asked to support biweekly payments changes the schedule loop and a migration in one diff, and the unique key on attempts keeps whatever it writes from adding a fourth presentment.
Best fit: Lending teams that collect installments by ACH and want schedules, attempts and returns handled in a service that runs in their own AWS or GCP account.
Check the interest method against your loan agreement, since this example uses a fixed monthly rate on the remaining balance and some products accrue daily or use a different day count. Authenticate the events endpoint with the processor's signature before it changes balances, and record the 180 day window from the original settlement date so a retry never goes out after it. Returns such as R10 for an unauthorized debit should also turn off autopay until the borrower authorizes again. Weekend and holiday due dates need a business day rule, and late fees, partial payments and payoff quotes each need their own entries in a ledger, which the double-entry ledger guide covers.
Compute the fixed payment from the principal, the periodic rate and the number of periods, then for each period charge interest on the remaining balance, rounded to the cent, and apply the rest to principal. The last installment takes whatever principal is left, so the schedule repays the loan exactly.
Under the Nacha Operating Rules, a debit returned for insufficient funds (R01) or uncollected funds (R09) may be reinitiated at most two times after the original return, for three presentments in total, within 180 days of the original settlement date. Most other return codes, such as an unauthorized debit, may not be retried without a new authorization.
Create one attempt row per presentment with a unique key on the loan, the installment and the attempt number, and send its ID as the idempotency key to the payment processor. A rerun of the job finds the open attempt and creates nothing, and a retried message reuses the same key.
Build it with Encore, declaring the database, the collection topic and the daily autopay cron job in code, and deploy it to your own AWS or GCP account. encore run starts Postgres locally, so attempts and returns can be tested before anything reaches the processor. Cron jobs do not run locally or in preview environments.
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.