Run scheduled jobs next to a Go Fiber v3 API, such as purge reminders and a nightly purge after a 30-day grace period, with Encore cron jobs, robfig/cron or EventBridge Scheduler.

Fiber apps pick up scheduled work early: reminders before a trial ends, cleanups of expired data, a nightly export. The tempting setup is robfig/cron started next to app.Listen, which works on one instance and runs the job once per replica as soon as the API scales out, and moving the schedule outside the process on AWS means EventBridge Scheduler, a separate task definition and IAM to run it.
This guide adds two scheduled jobs to a Fiber v3 API that deletes accounts after a 30-day grace period: an hourly job that reminds users three days before their data is purged and a nightly job that purges accounts in batches. It starts with Encore, where the schedule is declared in Go and runs on Encore's managed cron in your deployed environments, then shows robfig/cron and EventBridge Scheduler.
Encore works alongside Fiber, so the account routes stay Fiber handlers mounted in one fallback route, and each scheduled job is a private endpoint with a cron job declared next to it. Cron jobs are managed by the Encore platform, which calls the endpoint on schedule in each deployed environment. Encore provisions an IAM role for the service, or a service account on GCP.
Run in your terminal to get started locally.
The table stores when an account becomes eligible for purge and when its reminder went out, with a partial index so the jobs only scan accounts that are scheduled:
-- accounts/migrations/1_create_accounts.up.sql
CREATE TABLE accounts (
id BIGSERIAL PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
purge_after TIMESTAMPTZ,
purge_reminder_sent TIMESTAMPTZ
);
CREATE INDEX accounts_purge_after_idx ON accounts (purge_after) WHERE purge_after IS NOT NULL;
The Fiber routes start and cancel the grace period, and the two jobs do the scheduled work. SendPurgeReminders claims each reminder with a conditional UPDATE ... RETURNING, so a second run in the same hour finds nothing to send, and PurgeAccounts deletes in batches of 500 with FOR UPDATE SKIP LOCKED, which keeps each transaction short and lets an overlapping run take different rows:
// accounts/accounts.go
package accounts
import (
"context"
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"errors"
"net/http"
"strconv"
"strings"
"time"
"encore.dev/beta/auth"
"encore.dev/beta/errs"
"encore.dev/cron"
"encore.dev/rlog"
"encore.dev/storage/sqldb"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/adaptor"
)
var db = sqldb.NewDatabase("accounts", sqldb.DatabaseConfig{
Migrations: "./migrations",
})
var secrets struct {
SessionKey string
}
//encore:authhandler
func AuthHandler(ctx context.Context, token string) (auth.UID, error) {
uid, err := userIDFromToken(token)
if err != nil {
return "", &errs.Error{Code: errs.Unauthenticated, Message: "invalid token"}
}
return uid, nil
}
func userIDFromToken(token string) (auth.UID, error) {
if secrets.SessionKey == "" {
return "", errors.New("auth secret not set")
}
parts := strings.Split(token, ".")
if len(parts) != 3 {
return "", errors.New("invalid token")
}
id, expStr, sig := parts[0], parts[1], parts[2]
if id == "" || strings.ContainsAny(id, "/ \t\n") {
return "", errors.New("invalid token")
}
exp, err := strconv.ParseInt(expStr, 10, 64)
if err != nil || exp <= time.Now().Unix() {
return "", errors.New("invalid token")
}
mac := hmac.New(sha256.New, []byte(secrets.SessionKey))
mac.Write([]byte(id + "." + expStr))
expected := hex.EncodeToString(mac.Sum(nil))
if subtle.ConstantTimeCompare([]byte(sig), []byte(expected)) != 1 {
return "", errors.New("invalid token")
}
return auth.UID(id), nil
}
//encore:service
type Service struct {
handler http.HandlerFunc
}
func initService() (*Service, error) {
app := fiber.New()
app.Post("/accounts/:id/delete", scheduleDeletion)
app.Post("/accounts/:id/restore", cancelDeletion)
return &Service{handler: adaptor.FiberApp(app)}, nil
}
//encore:api public raw auth path=/!fallback
func (s *Service) Fallback(w http.ResponseWriter, req *http.Request) {
s.handler(w, req)
}
func accountIDForCaller(c fiber.Ctx) (int64, error) {
uid, ok := auth.UserID()
if !ok {
return 0, fiber.ErrUnauthorized
}
id, err := strconv.ParseInt(c.Params("id"), 10, 64)
if err != nil {
return 0, fiber.ErrNotFound
}
caller, err := strconv.ParseInt(string(uid), 10, 64)
if err != nil || caller != id {
return 0, fiber.ErrForbidden
}
return id, nil
}
// Deleting an account starts a 30-day grace period instead of removing data at once.
func scheduleDeletion(c fiber.Ctx) error {
id, err := accountIDForCaller(c)
if err != nil {
return err
}
res, err := db.Exec(c.Context(), `
UPDATE accounts
SET purge_after = now() + interval '30 days', purge_reminder_sent = NULL
WHERE id = $1 AND purge_after IS NULL`, id)
if err != nil {
return err
}
if res.RowsAffected() == 0 {
return c.Status(fiber.StatusConflict).JSON(fiber.Map{"error": "account not found or already scheduled"})
}
return c.Status(fiber.StatusAccepted).JSON(fiber.Map{"status": "scheduled", "days": 30})
}
func cancelDeletion(c fiber.Ctx) error {
id, err := accountIDForCaller(c)
if err != nil {
return err
}
res, err := db.Exec(c.Context(), `
UPDATE accounts SET purge_after = NULL, purge_reminder_sent = NULL
WHERE id = $1 AND purge_after > now()`, id)
if err != nil {
return err
}
if res.RowsAffected() == 0 {
return c.Status(fiber.StatusConflict).JSON(fiber.Map{"error": "nothing to restore"})
}
return c.JSON(fiber.Map{"status": "restored"})
}
// Every hour, remind accounts that will be purged within three days.
var _ = cron.NewJob("purge-reminders", cron.JobConfig{
Title: "Remind accounts before they are purged",
Every: 1 * cron.Hour,
Endpoint: SendPurgeReminders,
})
//encore:api private
func SendPurgeReminders(ctx context.Context) error {
// The conditional UPDATE claims each reminder once, even if the job runs twice.
rows, err := db.Query(ctx, `
UPDATE accounts SET purge_reminder_sent = now()
WHERE purge_after > now()
AND purge_after < now() + interval '3 days'
AND purge_reminder_sent IS NULL
RETURNING email, purge_after`)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var email string
var purgeAfter time.Time
if err := rows.Scan(&email, &purgeAfter); err != nil {
return err
}
// Hand the reminder to your email provider or a Pub/Sub topic here.
rlog.Info("purge reminder", "email", email, "purge_after", purgeAfter)
}
return rows.Err()
}
// Every night at 03:00 UTC, delete accounts whose grace period has ended.
var _ = cron.NewJob("purge-accounts", cron.JobConfig{
Title: "Purge accounts after the grace period",
Schedule: "0 3 * * *",
Endpoint: PurgeAccounts,
})
type PurgeResult struct {
Purged int `json:"purged"`
}
//encore:api private
func PurgeAccounts(ctx context.Context) (*PurgeResult, error) {
total := 0
for {
// Small batches keep each transaction short; SKIP LOCKED lets a
// second run work on other rows instead of waiting.
res, err := db.Exec(ctx, `
DELETE FROM accounts WHERE id IN (
SELECT id FROM accounts
WHERE purge_after <= now()
ORDER BY purge_after
LIMIT 500
FOR UPDATE SKIP LOCKED
)`)
if err != nil {
return nil, err
}
n := int(res.RowsAffected())
total += n
if n < 500 {
break
}
}
rlog.Info("accounts purged", "count", total)
return &PurgeResult{Purged: total}, nil
}
encore run starts Postgres locally and serves the Fiber routes, but cron jobs do not run locally or in preview environments, so you test a job by calling its endpoint from the local development dashboard. Schedules use either Every, which has to divide 24 hours evenly, or a cron expression evaluated in UTC. Job endpoints take no parameters, and a job can be called more than once under some network conditions, so the claim in the SQL matters as much as the schedule. The database is provisioned as RDS on AWS or Cloud SQL on GCP in your own account.
For an agent, a new schedule is a cron.NewJob and an endpoint in the same package as the data it touches, which a reviewer can read in one diff, and the endpoint can be called locally against a real Postgres before the job ever runs on a schedule.
Best fit: Fiber APIs that need scheduled jobs to run exactly once per tick across replicas, declared in Go next to the code they call.
robfig/cron v3 is the common in-process scheduler in Go, and it is a few lines next to the Fiber app:
package main
import (
"context"
"log"
"os"
"time"
"github.com/gofiber/fiber/v3"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/robfig/cron/v3"
)
func main() {
pool, err := pgxpool.New(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
// Runs inside every replica of the API, in the server's time zone
// unless you set one.
c := cron.New(cron.WithLocation(time.UTC))
c.AddFunc("0 3 * * *", func() {
tag, err := pool.Exec(context.Background(), `
DELETE FROM accounts WHERE id IN (
SELECT id FROM accounts WHERE purge_after <= now()
ORDER BY purge_after LIMIT 500 FOR UPDATE SKIP LOCKED)`)
if err != nil {
log.Println("purge:", err)
return
}
log.Println("purged", tag.RowsAffected())
})
c.Start()
defer c.Stop()
app := fiber.New()
// ... account routes ...
log.Fatal(app.Listen(":8080"))
}
It uses the server's local time zone unless you pass cron.WithLocation, the job dies with the process during a deploy, and every replica runs its own copy. The batched SKIP LOCKED delete keeps overlapping runs from doing the same rows twice, and an advisory lock around the whole tick stops more than one replica from starting the job at all:
func purgeWithLock(ctx context.Context, pool *pgxpool.Pool) {
const purgeLock = int64(0x7075726765) // "purge"
var got bool
if err := pool.QueryRow(ctx, `SELECT pg_try_advisory_lock($1)`, purgeLock).Scan(&got); err != nil || !got {
return
}
defer pool.Exec(ctx, `SELECT pg_advisory_unlock($1)`, purgeLock)
for {
tag, err := pool.Exec(ctx, `
DELETE FROM accounts WHERE id IN (
SELECT id FROM accounts WHERE purge_after <= now()
ORDER BY purge_after LIMIT 500 FOR UPDATE SKIP LOCKED)`)
if err != nil {
log.Println("purge:", err)
return
}
if tag.RowsAffected() == 0 {
return
}
log.Println("purged", tag.RowsAffected())
}
}
Best fit: a single-instance Fiber service where a missed or duplicated run causes no harm, or a small cluster that can take an advisory lock.
On AWS, EventBridge Scheduler can start a one-off ECS task from a cron expression in any time zone, which keeps the schedule out of the API process. The ECS guide for scheduled tasks covers the pieces: a task definition, a scheduler role allowed to call ecs:RunTask and pass the task's roles, and the subnets and security groups the task starts in.
Put the job in the same image as the API, behind a command argument, so the web process never runs the schedule:
// cmd/api/main.go
func main() {
ctx := context.Background()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
if len(os.Args) > 1 && os.Args[1] == "purge-accounts" {
purgeWithLock(ctx, pool)
return
}
app := fiber.New()
// ... account routes ...
log.Fatal(app.Listen(":8080"))
}
The scheduler then starts that command on a UTC cron, in the private subnets where the task can reach RDS, and does not assign a public IP:
resource "aws_scheduler_schedule" "purge_accounts" {
name = "fiber-purge-accounts"
schedule_expression = "cron(0 3 * * ? *)"
schedule_expression_timezone = "UTC"
flexible_time_window { mode = "OFF" }
retry_policy {
maximum_event_age_in_seconds = 3600
maximum_retry_attempts = 2
}
target {
arn = aws_ecs_cluster.api.arn
role_arn = aws_iam_role.scheduler_ecs.arn
ecs_parameters {
task_definition_arn = aws_ecs_task_definition.purge.arn
launch_type = "FARGATE"
network_configuration {
subnets = var.private_subnet_ids
security_groups = [aws_security_group.api.id]
assign_public_ip = false
}
}
}
}
The purge task definition uses the same image as the API, sets command = ["purge-accounts"], and injects DATABASE_URL from Secrets Manager. The scheduler role needs ecs:RunTask on that task definition and iam:PassRole on the task's execution and task roles. A failed run shows up in the task's stopped reason and CloudWatch logs. Runs happen once regardless of how many API replicas exist, and the task has its own CPU and memory, which suits a long purge better than a request handler. The hourly reminder job is a second schedule and a second task definition, with command = ["send-reminders"] pointing at another argument in the same binary, and the same SKIP LOCKED claim so two overlapping scheduler retries cannot email the same account twice. If you want a dead-letter for failed attempts, point the schedule's retry policy at an SQS queue and alarm on that queue's depth.
Best fit: teams already running ECS in Terraform that want long or heavy jobs in their own task instead of the web process.
Pick Encore when the Fiber app needs scheduled jobs that run once per tick in deployed environments, declared in Go and backed by Postgres in your own AWS or GCP account. Cron jobs do not run locally or in preview environments. Pick robfig/cron for a single instance where the occasional duplicate or missed run is acceptable. Pick EventBridge Scheduler with ECS tasks when the job is long-running or heavy and the team already manages ECS in Terraform.
The quickest way is robfig/cron started next to app.Listen, but it runs in every replica, so with three instances the job runs three times. For production, trigger the job from one scheduler outside the process, such as EventBridge Scheduler starting an ECS task, and keep the job idempotent.
Write the job as a private Encore endpoint with the signature func(ctx context.Context) error, declare it with cron.NewJob and either Every or a Schedule cron expression, and keep the Fiber routes mounted in a raw fallback endpoint. Encore calls the endpoint on schedule in your deployed environments; cron jobs do not run locally or in preview environments, so you call the endpoint by hand to test it. Cron expressions are evaluated in UTC, and intervals set with Every must divide 24 hours evenly, such as 1 * cron.Hour or 10 * cron.Minute.
Make each unit of work claim itself in the database. A conditional UPDATE ... SET reminder_sent = now() WHERE reminder_sent IS NULL RETURNING ... only returns rows that have not been handled, so a second run in the same hour finds nothing, and DELETE batches with FOR UPDATE SKIP LOCKED let overlapping runs split the rows.
Pick one time zone and set it explicitly. robfig/cron uses the server's local time zone unless you pass cron.WithLocation, EventBridge Scheduler can run in any time zone you configure, and a UTC schedule is the simplest way to keep local and production in agreement.
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.