Firebase scheduled functions are useful for recurring work such as cleanup, notifications, report generation, and subscription checks—but a schedule alone does not make a workflow reliable. This guide provides a reusable checklist for defining schedules, handling time zones, preventing duplicate processing, configuring retries, testing locally, and reviewing deployments before production.
Overview
Firebase scheduled functions use Cloud Scheduler to trigger Cloud Functions on a recurring schedule. In the Functions SDK, the usual implementation is a scheduled handler created with onSchedule. You can express a schedule with a cron string or a human-readable interval, and you can specify a time zone when the job must follow local calendar time.
A scheduled invocation should be treated as a request to begin work, not as proof that the work has completed exactly once. A trigger can be delayed, retried, or reach a function while an earlier execution is still running. Your function therefore needs an explicit strategy for duplicate delivery, partial completion, and overlapping runs.
A minimal second-generation example looks like this:
const { onSchedule } = require("firebase-functions/v2/scheduler");
exports.removeExpiredRecords = onSchedule(
{
schedule: "every 24 hours",
timeZone: "Etc/UTC",
region: "us-central1"
},
async (event) => {
// Find a bounded batch of expired records.
// Process each record with an idempotent operation.
}
);Check the Firebase Functions and Cloud Scheduler documentation for the currently supported SDK syntax, runtime options, regions, and quotas before deploying. These details can change independently of your application code.
Checklist by scenario
For a new scheduled function
- Define the business event. Write down what “daily” or “hourly” means. A billing reminder, for example, may need a local date rather than a fixed UTC interval.
- Choose the schedule deliberately. Use a human-readable interval for simple recurring work. Use cron when you need a specific minute, hour, weekday, or month.
- Choose a time zone. Use UTC for machine-oriented windows and globally consistent processing. Use an IANA time-zone identifier when the schedule follows a customer or business region.
- Bound the workload. Process a page or batch instead of scanning an unbounded collection in one invocation. Record a cursor, status, or next-run marker when the work may exceed a single execution.
- Make the operation idempotent. Store a stable job key, source event ID, period, or completion marker so a retry can safely repeat the handler.
- Set an execution policy. Decide what should happen after a transient failure, how many times work may be retried, and whether a failed item should be isolated from the rest of the batch.
- Log an execution identifier. Include the scheduled job name, logical period, batch size, start time, and outcome in structured logs.
For local development and testing
- Keep the scheduled handler's business logic in a plain function that accepts dependencies and a clock. Test that function without waiting for a real schedule.
- Use the Firebase Emulator Suite to exercise Firestore, Authentication, and other local dependencies where supported. The Firebase Emulator Suite Testing Guide covers seed data and CI test matrices.
- Test an empty batch, a partial batch, a failed item, a repeated invocation, and an invocation that begins while a previous run is unfinished.
- Use a fixed test clock for date boundaries. Include the day before and after daylight-saving changes if the job uses a local time zone.
- For manual testing, invoke the underlying service through a controlled test path rather than changing the production schedule to run immediately.
For a production deployment
- Confirm that the project is on the appropriate billing plan and that required APIs and permissions are enabled. Verify current Firebase and Google Cloud pricing and quotas in the official console or documentation rather than copying old estimates.
- Deploy only the intended function, for example
firebase deploy --only functions:removeExpiredRecords. - Review the generated or updated Cloud Scheduler job and confirm its schedule, time zone, region, target, and retry settings.
- Set alerts for failures, excessive duration, unusual invocation volume, and backlog growth. Logs should make it possible to distinguish an empty successful run from a failed run.
- Run a controlled post-deployment check against a small, safe data set. Confirm both the expected side effect and the recorded idempotency marker.
For a manual or administrative trigger
A scheduled function is not the same as a callable function. If operators need a “run now” endpoint, expose a separate authenticated administrative path or use a controlled Cloud Run or Cloud Functions HTTP endpoint. Validate identity, authorization, input, and replay protection on that path. Do not rely on a hidden URL or a client-side secret. Review access patterns with the Firebase Security Rules Audit, while remembering that server-side Admin SDK operations are not limited by Firestore Security Rules.
What to double-check
Cron expressions and time zones
Traditional cron fields are commonly written as minute, hour, day of month, month, and day of week. Examples include:
| Expression | Meaning |
|---|---|
0 * * * * | At the start of every hour |
15 2 * * * | At 02:15 every day |
0 9 * * 1-5 | At 09:00 Monday through Friday |
30 1 1 * * | At 01:30 on the first day of each month |
Confirm the scheduler's cron interpretation and time-zone setting before relying on an expression. A job scheduled for 02:30 in a daylight-saving region may encounter a skipped or repeated local time. If the business process cannot tolerate ambiguity, schedule in UTC and calculate the business period explicitly in code.
Retries and partial completion
Retries are valuable for transient failures, but they can repeat side effects. Write each step so that it can safely be attempted again. For a Firestore-backed task, a common pattern is to create a document such as jobRuns/{jobName_period_itemId} with a unique key. Use a transaction or conditional write to claim the item, then record completion and error information. Design the claim state so a crashed worker can eventually be retried rather than leaving the item permanently locked.
Do not mark a whole batch successful merely because the function reached the end of its loop. Record per-item outcomes or move failed items to a retry collection with an attempt count and next-attempt time. If an external API is involved, use that provider's idempotency key when available.
Overlapping executions
Estimate the maximum runtime and compare it with the schedule interval. If a job can run longer than its interval, overlapping executions are possible. Choose one of three explicit approaches: make the work safely concurrent, use a distributed lease or lock with an expiry, or reduce each invocation to a bounded queue of tasks. A lock without an expiry can create a permanent stall after a crash; a lock with no ownership check can allow two workers to release or overwrite one another's state.
Observability and cost
Track invocation count, duration, error count, processed items, skipped duplicates, and remaining backlog. Scheduled functions can generate costs from compute, invocations, database reads and writes, outbound services, and scheduler-related resources, depending on the products and configuration involved. Revisit the current Firebase pricing page and project usage reports before approving a high-frequency or high-volume design. The Firebase Cost Optimization Guide provides a broader review framework.
Common mistakes
- Assuming exactly-once execution: Treat every scheduled invocation as potentially repeatable.
- Using local time without a calendar test: Daylight-saving transitions and month boundaries can expose incorrect date calculations.
- Scanning an entire collection: Large scans increase runtime, cost, and the chance of timeout. Prefer indexed queries, pagination, and checkpoints.
- Putting all work in one transaction: Long transactions and large batches are fragile. Claim and complete smaller units of work.
- Returning success after swallowing errors: If the function reports success while items failed, scheduler-level retries may never occur. Preserve failure signals and record item-level errors.
- Exposing a public run-now endpoint: Require strong authentication and authorization, validate requests, and protect against replay.
- Testing only the happy path: Simulate duplicate delivery, timeout, partial failure, empty results, and an unavailable dependency.
- Changing a schedule without a migration plan: A new cadence can create duplicate periods or leave a gap. Record the last processed period and reconcile after deployment.
When to revisit
Keep this checklist with the function's deployment notes and review it before seasonal planning cycles, major traffic changes, billing or reporting periods, and any change to a workflow or its dependencies. Recheck schedules whenever a team changes time zones, business hours, retry behavior, data retention, or the function's region.
After changing a schedule, compare the old and new next-run times, identify any missed or duplicated business periods, and run a reconciliation query. After changing the Functions SDK, runtime, or deployment configuration, verify the generated scheduler job and perform a controlled test. Review logs after the first several production runs, then periodically inspect duration, failure, duplicate-skip, and backlog metrics.
Before shipping, use this short sign-off list: schedule and time zone are documented; workload is bounded; duplicate processing is safe; retries and overlap behavior are intentional; manual access is protected; logs and alerts identify failures; emulator and failure-path tests pass; and current pricing, quotas, runtime support, and deployment behavior have been checked. That process turns a Firebase cron job from a timer into a maintainable serverless workflow.