Design a payroll run that is opened once per pay period, calculated in one transaction, approved by a second person and paid out exactly once per payslip, then implement it in Go with the database, queue and cron job in your own AWS or GCP account.

A payroll run turns a pay period, a list of employees and their deductions into payslips and bank transfers. The cost of a bug is specific: an employee paid twice, or paid the wrong amount, is hard to unwind once the money has left the account, and a run must not pay out before anyone has approved it.
This guide designs the run as a small state machine backed by Postgres constraints, so the database refuses the mistakes the code might make. It then implements the run, the approval and the payouts in Go with Encore, which provisions the database, the queue and the cron job in your own AWS or GCP account.
A run moves through five states, each change a conditional UPDATE that names the state it expects:
paid_at timestamp.Taxes and benefits come from a tax engine or your accountant's tables, such as the federal income tax withholding methods in IRS Publication 15-T and the employer tax rules in IRS Publication 15 in the US. The run treats them as deduction rows, which keeps tax logic out of the payout path. The example is illustrative: withholding, benefits and money movement rules differ by jurisdiction, and your payroll and compliance teams own the rates, the filings and the provider you use.
The partial unique index allows one live run per period, the CHECK constraint on approved_by rejects self-approval, and UNIQUE (run_id, employee_id) allows one payslip per person. Net pay is a generated column, so it cannot drift from gross minus deductions:
CREATE TABLE employees (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
annual_salary_cents BIGINT NOT NULL CHECK (annual_salary_cents >= 0),
bank_account_ref TEXT NOT NULL,
active BOOLEAN NOT NULL DEFAULT true
);
CREATE TABLE payroll_runs (
id BIGSERIAL PRIMARY KEY,
period_start DATE NOT NULL,
period_end DATE NOT NULL,
periods_per_year INT NOT NULL CHECK (periods_per_year IN (12, 24, 26, 52)),
status TEXT NOT NULL DEFAULT 'draft'
CHECK (status IN ('draft', 'calculated', 'approved', 'paid', 'cancelled')),
created_by TEXT NOT NULL,
approved_by TEXT,
CHECK (approved_by IS NULL OR approved_by <> created_by)
);
-- At most one live run per pay period.
CREATE UNIQUE INDEX one_live_run_per_period
ON payroll_runs (period_start, period_end)
WHERE status <> 'cancelled';
CREATE TABLE payslips (
id BIGSERIAL PRIMARY KEY,
run_id BIGINT NOT NULL REFERENCES payroll_runs(id),
employee_id TEXT NOT NULL REFERENCES employees(id),
gross_cents BIGINT NOT NULL,
deductions_cents BIGINT NOT NULL DEFAULT 0,
net_cents BIGINT GENERATED ALWAYS AS (gross_cents - deductions_cents) STORED,
paid_at TIMESTAMPTZ,
UNIQUE (run_id, employee_id),
CHECK (deductions_cents <= gross_cents)
);
CREATE TABLE deductions (
employee_id TEXT NOT NULL REFERENCES employees(id),
kind TEXT NOT NULL,
amount_cents BIGINT NOT NULL CHECK (amount_cents >= 0),
PRIMARY KEY (employee_id, kind)
);
Run against Postgres 17, a second run for November 2026 was rejected by the index, self-approval was rejected by the CHECK, calculating twice left one payslip per employee (650000 gross, 180000 deductions and 470000 net cents for a $78,000 salary paid monthly), recalculation after approval matched no rows, and the run closed as paid only after its last payslip was paid.
On AWS the pieces are RDS for PostgreSQL with the schema above, an API on ECS Fargate or Lambda behind an authorizer, an SQS queue with a dead-letter queue for payouts, a worker that calls the payouts provider, a scheduled Lambda function for the hourly reconcile, the provider key in Secrets Manager and IAM policies for each function or task. The double-entry ledger guide and marketplace payouts guide cover the money side in more depth.
Encore is a backend framework with built-in infrastructure for Go and TypeScript. The database, the payouts topic, the subscription, the cron job and the provider secret are declared in the service code, and deploying to your AWS or GCP account provisions RDS or Cloud SQL and SNS with SQS or Pub/Sub. Encore provisions an IAM role for the service.

Run in your terminal to get started locally.
The endpoints use an auth handler, so auth.UserID() returns the signed-in payroll admin. Approval and publishing are separate steps, and the hourly reconcile republishes any payslip whose message was lost between them:
package payroll
import (
"context"
"time"
"encore.dev/beta/auth"
"encore.dev/beta/errs"
"encore.dev/cron"
"encore.dev/pubsub"
"encore.dev/storage/sqldb"
)
var db = sqldb.NewDatabase("payroll", sqldb.DatabaseConfig{Migrations: "./migrations"})
type PayoutRequested struct {
PayslipID int64
}
var payouts = pubsub.NewTopic[*PayoutRequested]("payout-requested", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
type CreateRunParams struct {
PeriodStart time.Time `json:"period_start"`
PeriodEnd time.Time `json:"period_end"`
PeriodsPerYear int `json:"periods_per_year"`
}
type Run struct {
ID int64 `json:"id"`
Status string `json:"status"`
}
// CreateRun opens a draft run. The partial unique index rejects
// a second live run for the same period.
//
//encore:api auth method=POST path=/runs
func CreateRun(ctx context.Context, p *CreateRunParams) (*Run, error) {
uid, _ := auth.UserID()
r := &Run{Status: "draft"}
err := db.QueryRow(ctx, `
INSERT INTO payroll_runs (period_start, period_end, periods_per_year, created_by)
VALUES ($1, $2, $3, $4) RETURNING id`,
p.PeriodStart, p.PeriodEnd, p.PeriodsPerYear, string(uid)).Scan(&r.ID)
if err != nil {
return nil, err
}
return r, nil
}
// Calculate writes one payslip per active employee in a single transaction.
// Rerunning it on a calculated run replaces the payslips.
//
//encore:api auth method=POST path=/runs/:id/calculate
func Calculate(ctx context.Context, id int64) (*Run, error) {
tx, err := db.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
res, err := tx.Exec(ctx, `
UPDATE payroll_runs SET status = 'calculated'
WHERE id = $1 AND status IN ('draft', 'calculated')`, id)
if err != nil {
return nil, err
}
if res.RowsAffected() == 0 {
return nil, &errs.Error{Code: errs.FailedPrecondition, Message: "run is not editable"}
}
if _, err := tx.Exec(ctx, `DELETE FROM payslips WHERE run_id = $1`, id); err != nil {
return nil, err
}
// Gross is the salary divided by pay periods, rounded down to the cent.
// Taxes and benefits come from your tax engine as deduction rows.
_, err = tx.Exec(ctx, `
INSERT INTO payslips (run_id, employee_id, gross_cents, deductions_cents)
SELECT r.id, e.id,
e.annual_salary_cents / r.periods_per_year,
LEAST(COALESCE(sum(d.amount_cents), 0), e.annual_salary_cents / r.periods_per_year)
FROM payroll_runs r
JOIN employees e ON e.active
LEFT JOIN deductions d ON d.employee_id = e.id
WHERE r.id = $1
GROUP BY r.id, e.id`, id)
if err != nil {
return nil, err
}
return &Run{ID: id, Status: "calculated"}, tx.Commit()
}
// Approve needs a second person: the CHECK constraint rejects
// approval by the user who created the run.
//
//encore:api auth method=POST path=/runs/:id/approve
func Approve(ctx context.Context, id int64) (*Run, error) {
uid, _ := auth.UserID()
res, err := db.Exec(ctx, `
UPDATE payroll_runs SET status = 'approved', approved_by = $2
WHERE id = $1 AND status = 'calculated' AND created_by <> $2`, id, string(uid))
if err != nil {
return nil, err
}
if res.RowsAffected() == 0 {
return nil, &errs.Error{Code: errs.PermissionDenied, Message: "run must be calculated and approved by someone else"}
}
rows, err := db.Query(ctx, `SELECT id FROM payslips WHERE run_id = $1 AND net_cents > 0`, id)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var slip int64
if err := rows.Scan(&slip); err != nil {
return nil, err
}
if _, err := payouts.Publish(ctx, &PayoutRequested{PayslipID: slip}); err != nil {
return nil, err
}
}
return &Run{ID: id, Status: "approved"}, rows.Err()
}
// Reconcile republishes payouts for approved runs that still have unpaid
// payslips, covering a crash between the approval and the last publish.
//
//encore:api private
func Reconcile(ctx context.Context) error {
rows, err := db.Query(ctx, `
SELECT p.id FROM payslips p
JOIN payroll_runs r ON r.id = p.run_id
WHERE r.status = 'approved' AND p.paid_at IS NULL AND p.net_cents > 0`)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var slip int64
if err := rows.Scan(&slip); err != nil {
return err
}
if _, err := payouts.Publish(ctx, &PayoutRequested{PayslipID: slip}); err != nil {
return err
}
}
return rows.Err()
}
// Scheduled by the Encore platform once deployed.
var _ = cron.NewJob("reconcile-payouts", cron.JobConfig{
Title: "Republish unpaid payouts",
Every: 1 * cron.Hour,
Endpoint: Reconcile,
})
The subscription loads the unpaid payslip, calls the provider with the payslip ID as the idempotency key and marks it paid. A duplicate message finds paid_at set and returns:
package payroll
import (
"context"
"errors"
"fmt"
"time"
"encore.dev/pubsub"
"encore.dev/storage/sqldb"
)
var secrets struct {
PayoutsAPIKey string
}
var _ = pubsub.NewSubscription(payouts, "send-payout", pubsub.SubscriptionConfig[*PayoutRequested]{
Handler: sendPayout,
MaxConcurrency: 10,
RetryPolicy: &pubsub.RetryPolicy{MinBackoff: time.Minute, MaxRetries: 20},
})
func sendPayout(ctx context.Context, msg *PayoutRequested) error {
var runID, net int64
var account string
err := db.QueryRow(ctx, `
SELECT p.run_id, p.net_cents, e.bank_account_ref
FROM payslips p JOIN employees e ON e.id = p.employee_id
WHERE p.id = $1 AND p.paid_at IS NULL`, msg.PayslipID).Scan(&runID, &net, &account)
if errors.Is(err, sqldb.ErrNoRows) {
return nil // paid by an earlier delivery
} else if err != nil {
return err
}
// The payslip ID is the idempotency key, so a retry after a timeout
// cannot pay the same employee twice.
key := fmt.Sprintf("payslip-%d", msg.PayslipID)
if err := providerTransfer(ctx, key, account, net); err != nil {
return err
}
if _, err := db.Exec(ctx,
`UPDATE payslips SET paid_at = now() WHERE id = $1 AND paid_at IS NULL`, msg.PayslipID); err != nil {
return err
}
// Close the run once its last payslip is paid.
_, err = db.Exec(ctx, `
UPDATE payroll_runs SET status = 'paid'
WHERE id = $1 AND status = 'approved'
AND NOT EXISTS (SELECT 1 FROM payslips
WHERE run_id = $1 AND paid_at IS NULL AND net_cents > 0)`, runID)
return err
}
// providerTransfer calls your payouts provider with secrets.PayoutsAPIKey
// and the idempotency key. Replace with the provider's SDK.
func providerTransfer(ctx context.Context, idempotencyKey, account string, cents int64) error {
_ = secrets.PayoutsAPIKey
return nil
}
The databases, Pub/Sub, cron jobs and secrets docs cover each primitive. The cron job is scheduled by the Encore platform once deployed and does not run locally. The provider key is set with encore secret set --type prod PayoutsAPIKey and kept in the cloud's secrets manager. Production values are not stored in the repository, so a coding agent working on the payroll code cannot read or leak those production values. A local override in .secrets.local.cue is a file on disk and is readable if it is present.
A coding agent that adds a bonus run type or a new deduction source edits the Go code and the migration, and the constraints above still reject a double payment if the change has a bug.
Best fit: HR and fintech teams building payroll or contractor payouts in Go or TypeScript who want the money data in their own AWS or GCP account.
Model each pay period as a payroll run that moves from draft to calculated to approved to paid. Calculation writes one payslip per employee in a single transaction, approval requires a different person from the creator, and each payslip is paid by a queued payout that uses the payslip ID as its idempotency key.
Guard it in three places: a unique constraint on run and employee allows only one payslip per person per run, the payout call sends the payslip ID as the provider's idempotency key, and the paid_at update only matches unpaid payslips. A retried or duplicated message then finds the payslip paid and does nothing.
No. Store money as integer cents in a BIGINT column and round with a stated rule, such as dividing annual salary by pay periods and truncating to the cent. Floating-point values cannot represent most decimal amounts exactly, and the differences show up when payslips are summed against the bank file.
Declare the Postgres database, the payouts topic and subscription, the reconcile cron job and the payouts provider secret in Go. Deploying to your AWS or GCP account provisions RDS or Cloud SQL and SNS with SQS or Pub/Sub, stores the secret in the cloud's secrets manager and runs the cron job on the Encore platform.
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.