
A scheduled background worker is a common requirement in backend development.
You might need to synchronize data from an external API, periodically update records in a database, or run maintenance tasks without manually triggering an endpoint. A typical solution involves combining a JavaScript runtime, an HTTP client, a scheduling library, and a database driver. But what if your runtime already provides these capabilities? In this tutorial, we'll build a scheduled data synchronization worker using [Fairyfly](https://www.fairyfly.dev/). We'll use: - **`ff.cron`** — Fairyfly's built-in job scheduler. - **Native `fetch`** — To retrieve data from an external API. - **PostgreSQL (`sql`)** — To persist synchronized records. - **Scoped permissions** — To control which network destinations and environment variables the application can access. - **Standalone compilation** — To package the application into a single executable. No cron package. No HTTP client dependency. No PostgreSQL driver. Just JavaScript and Fairyfly. ## 1. The project We'll build a small worker that periodically fetches posts from an external API and synchronizes them into a PostgreSQL database. Our workflow: 1. Retrieve posts from an external API. 2. Validate the response. 3. Insert new records into PostgreSQL. 4. Update existing records when their content changes. 5. Repeat the process automatically every five minutes. For this example, we'll use [JSONPlaceholder](https://jsonplaceholder.typicode.com/), a free fake REST API that provides sample data. The goal isn't to build a complete production synchronization platform. It's to demonstrate how Fairyfly's built-in capabilities work together in a realistic backend workload. ## 2. Install Fairyfly First, install Fairyfly using its installation script: bash curl -fsSL https://www.fairyfly.dev/install.sh | sh Verify the installation: ff --version You should see your installed Fairyfly version. For this tutorial, we're targeting Fairyfly v0.4.0. 3. Prepare PostgreSQL We'll use PostgreSQL to store the synchronized records. You can use an existing PostgreSQL instance or start a local development database with Docker: docker run \ --name fairyfly-postgres \ -e POSTGRES_USER=postgres \ -e POSTGRES_PASSWORD=fairyfly \ -e POSTGRES_DB=sync_demo \ -p 5432:5432 \ -d postgres:17-alpine Wait until PostgreSQL is ready before continuing. Our application will use a connection string: export DATABASE_URL="postgres://postgres:fairyfly@127.0.0.1:5432/sync_demo" Notice that we're using 127.0.0.1, rather than localhost. This matters because Fairyfly's network permissions match the literal hostname configured in the connection string. 4. Create the worker Create a file called sync.js. We'll keep the entire application in this single file. const API_URL = "https://jsonplaceholder.typicode.com/posts"; let syncInProgress = false; async function syncPosts() { if (syncInProgress) { console.log("[sync] Previous synchronization is still running."); return; } syncInProgress = true; const startedAt = performance.now(); try { console.log("[sync] Fetching external posts..."); const response = await fetch(API_URL); if (!response.ok) { throw new Error( `API returned HTTP ${response.status}` ); } const posts = await response.json(); if (!Array.isArray(posts)) { throw new Error("Unexpected API response"); } let synchronized = 0; for (const post of posts) { if ( !Number.isInteger(post.id) || !Number.isInteger(post.userId) || typeof post.title !== "string" || typeof post.body !== "string" ) { throw new Error("Invalid post received from API"); } await sql` INSERT INTO synced_posts ( external_id, user_id, title, body, synced_at ) VALUES ( ${post.id}, ${post.userId}, ${post.title}, ${post.body}, NOW() ) ON CONFLICT (external_id) DO UPDATE SET user_id = EXCLUDED.user_id, title = EXCLUDED.title, body = EXCLUDED.body, synced_at = NOW() `; synchronized++; } const duration = ( performance.now() - startedAt ).toFixed(2); console.log( `[sync] Successfully synchronized ${synchronized} posts in ${duration}ms` ); } catch (error) { console.error("[sync] Synchronization failed:", error); } finally { syncInProgress = false; } } async function main() { // Prepare the database table. await sql` CREATE TABLE IF NOT EXISTS synced_posts ( external_id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, title TEXT NOT NULL, body TEXT NOT NULL, synced_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ) `; // Register a recurring synchronization task. ff.cron( "posts-sync", "@every 5m", () => { console.log("[cron] Starting scheduled synchronization."); syncPosts(); } ); console.log("[cron] Registered posts-sync: every 5 minutes."); // Perform the first synchronization immediately. await syncPosts(); } main().catch((error) => { console.error("[startup] Worker initialization failed:", error); process.exit(1); }); Let's understand what's happening. 5. Using Fairyfly's native fetch API The first part of our worker retrieves data from an external API: const response = await fetch(API_URL); if (!response.ok) { throw new Error(`API returned HTTP ${response.status}`); } const posts = await response.json(); Fairyfly provides fetch as a global API. There is no need to install an additional HTTP client or import a package just to make an HTTP request. We also check response.ok because HTTP error responses, such as 404 and 500, resolve to a Response rather than automatically throwing an exception. One important detail: outbound network access is deny-by-default. We'll explicitly grant access to the API when launching the worker. Documentation: Fairyfly Fetch API https://www.fairyfly.dev/api/fetch. 6. Using the built-in PostgreSQL client The next part is where Fairyfly becomes particularly interesting. Instead of installing a PostgreSQL driver, we use its native sql global: await sql` INSERT INTO synced_posts ( external_id, user_id, title, body, synced_at ) VALUES ( ${post.id}, ${post.userId}, ${post.title}, ${post.body}, NOW() ) ON CONFLICT (external_id) DO UPDATE SET user_id = EXCLUDED.user_id, title = EXCLUDED.title, body = EXCLUDED.body, synced_at = NOW() `; The SQL tagged template automatically binds interpolated JavaScript values as parameters. This means we're not manually constructing SQL strings with user-controlled values. We're also using PostgreSQL's ON CONFLICT clause. Why? Because this is a synchronization task. Running it multiple times shouldn't create duplicate records. When a record already exists, PostgreSQL updates it instead. The sql global uses Fairyfly's native PostgreSQL client and connection pool. No separate JavaScript database package is required. Documentation: Fairyfly PostgreSQL API https://www.fairyfly.dev/api/postgres. 7. Scheduling jobs with ff.cron Now for the interesting part. We need our synchronization function to execute automatically. In many JavaScript applications, this means installing a scheduling library and configuring a recurring job. Fairyfly provides an in-process scheduler directly through ff.cron. ff.cron( "posts-sync", "@every 5m", () => { console.log("[cron] Starting scheduled synchronization."); syncPosts(); } ); The API accepts three arguments: • A name identifying the job. • A schedule. • A callback to execute. The @every 5m expression schedules the task at five-minute intervals. Fairyfly also supports standard five-field cron expressions, for example: // Every minute ff.cron("job-one", "* * * * *", () => { console.log("Running every minute"); }); // Every hour ff.cron("job-two", "0 * * * *", () => { console.log("Running every hour"); }); // Every day at midnight UTC ff.cron("job-three", "0 0 * * *", () => { console.log("Daily task"); }); The scheduler uses UTC scheduling. One more detail: the syncInProgress variable prevents a new synchronization from starting while the previous one is still running. This is useful when an external API or database takes longer than expected. Documentation: Fairyfly Cron API https://www.fairyfly.dev/api/cron. 8. Run the worker with explicit permissions Now that our application is ready, we need to launch it. Fairyfly uses a deny-by-default permission model. Our worker needs two network permissions: 1. Access to jsonplaceholder.typicode.com over HTTPS. 2. Access to our PostgreSQL instance on port 5432. It also needs permission to read the DATABASE_URL environment variable. (If --allow-env=DATABASE_URL is omitted, sql silently ignores DATABASE_URL and falls back to default connection settings.) Run: ff sync.js \ --allow-env=DATABASE_URL \ --allow-net=jsonplaceholder.typicode.com:443,127.0.0.1:5432 That's all. Notice what we didn't use: --allow-all Instead, we granted only the permissions required by our application. For a remote PostgreSQL instance, replace 127.0.0.1:5432 with the exact database hostname and port. For PostgreSQL TLS using sslmode=verify-full, provide the CA certificate in the connection string and grant access to its path with --allow-read. Documentation: Fairyfly Permissions https://www.fairyfly.dev/concepts/permissions. 9. Observe the worker When the worker starts, it first creates the database table, registers the scheduled job, and performs its initial synchronization. You should see output similar to: [cron] Registered posts-sync: every 5 minutes. [sync] Fetching external posts... [sync] Successfully synchronized 100 posts in 266.00ms The exact execution time will vary depending on your hardware, network, and database. After the first execution, the scheduler will trigger another synchronization according to the configured interval. You can inspect the database: SELECT external_id, title, synced_at FROM synced_posts ORDER BY external_id LIMIT 5; You should see the synchronized records. Because we're using an upsert operation, subsequent executions update existing records instead of creating duplicates. 10. Compile the worker into a standalone executable Fairyfly also provides a way to package JavaScript applications into standalone executables. Since our worker is contained in one JavaScript file and doesn't import external modules, we can use: ff compile sync.js --standalone -o sync-worker This produces a standalone executable containing the Fairyfly runtime and compiled application bytecode. Make sure DATABASE_URL is exported in your shell (or pass --env-file), then launch the binary directly: ./sync-worker \ --allow-env=DATABASE_URL \ --allow-net=jsonplaceholder.typicode.com:443,127.0.0.1:5432 The executable retains Fairyfly's permission model. It still needs the database connection string and the appropriate runtime permissions. This is useful when you want to distribute a small backend worker without separately deploying your JavaScript source and runtime installation. Documentation: Fairyfly CLI Reference https://www.fairyfly.dev/reference/cli. 11. Important considerations before production This example demonstrates the capabilities, but there are a few architectural considerations worth understanding. The scheduler is in-process. ff.cron schedules jobs within the running process. It is not a persistent distributed scheduler. If the process exits, its scheduled jobs disappear. They are registered again when the process starts. Multiple instances can execute the same job. If you deploy three replicas of this worker, each replica registers its own schedule. For workloads that must have a single scheduler, use an external scheduler or a distributed coordination mechanism. Handle failures explicitly. Our example logs synchronization failures and tries again on a future scheduled execution. It doesn't implement durable retries or a persistent job queue. For important business operations, consider transaction boundaries, retries, monitoring, and synchronization checkpoints. Make synchronization idempotent. The PostgreSQL upsert helps prevent duplicate records. For more complicated synchronization workflows, you'll also need to consider partial failures and atomicity. These considerations matter regardless of which JavaScript runtime you use. Conclusion We built a scheduled data synchronization worker using Fairyfly. In one JavaScript file, we combined: • Native HTTP requests through fetch. • A built-in PostgreSQL client. • In-process scheduling through ff.cron. • Explicit network and environment permissions. • Standalone executable compilation. Without installing a scheduling library, HTTP client, or PostgreSQL driver. This is one example of what becomes possible when essential backend capabilities are provided directly by the runtime. Fairyfly is an open-source, serverless-first JavaScript runtime built with Zig and powered by QuickJS. Explore the documentation and build something with it: • Fairyfly Documentation https://www.fairyfly.dev/ • GitHub Repository https://github.com/AbdElMajidOuhamane/ff • Fairyfly Cookbook https://www.fairyfly.dev/cookbook/index 
