Lesson 6 of 9 · 27m
AJAX, REST, Cron, and Background Work Without Request-Time Surprises
Choosing between admin-ajax and REST, designing idempotent endpoints, using wp-cron honestly, and moving heavy work out of user-facing requests.
WordPress can execute work in several contexts: browser page loads, admin-ajax, REST requests, cron events, WP-CLI, and sometimes system cron. Professional plugins choose deliberately. The wrong choice shows up as duplicate emails, timed-out imports, deadlocks, or background jobs that run only when somebody visits the site.
The guiding rule is simple: user-facing requests should acknowledge work, not perform unbounded work. Anything slow, retryable, or batch-oriented belongs in a queue.
admin-ajax is legacy but still useful
add_action('wp_ajax_acme_retry_batch', 'acme_retry_batch');
function acme_retry_batch(): void {
check_ajax_referer('acme_retry_batch', 'nonce');
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'Forbidden'], 403);
}
wp_send_json_success(['queued' => true]);
}wp_ajax_ is for authenticated sessions; wp_ajax_nopriv_ is unauthenticated and therefore dangerous by default. Most plugins do not need nopriv endpoints. If one exists, assume hostile internet traffic will hit it continuously.
REST is the better public contract
register_rest_route('acme/v1', '/batches/(?P<id>\d+)', [
'methods' => WP_REST_Server::READABLE,
'callback' => 'acme_get_batch',
'permission_callback' => function (WP_REST_Request $request) {
return current_user_can('edit_post', (int) $request['id']);
},
'args' => [
'id' => ['validate_callback' => 'is_numeric'],
],
]);REST gives you schemas, structured errors, discoverability, and consistent authentication. permission_callback is mandatory in modern WordPress for a reason. Do not return true because “the data is harmless”; headers, metadata, and user IDs are data too.
Return proper status codes. A 200 response containing { success: false } makes monitoring, client behavior, and debugging worse.
wp-cron is traffic-triggered, not a system scheduler
wp-cron.php runs when requests occur. Low-traffic sites miss schedules; high-traffic cached sites can stampede them. For production-critical jobs, disable web-triggered cron and use system cron:
* * * * * curl -fsS https://client-site.test/wp-cron.php?doing_wp_cron >/dev/null 2>&1Better yet, run wp cron event run --due-now through WP-CLI where available. In wp-config.php operators often set:
define('DISABLE_WP_CRON', true);Do not assume you control this. Your plugin must tolerate delayed, overlapping, and repeated cron execution.
Idempotency is the whole game
A retry should be safe. Store a batch state machine such as pending → running → complete | failed, include a unique job key, and make effects conditional:
$token = wp_generate_password(20, false);
$claimed = $wpdb->query($wpdb->prepare(
"UPDATE {$wpdb->prefix}acme_jobs SET status = 'running', worker = %s WHERE id = %d AND status = 'pending'",
$token,
$job_id
));
if ($claimed !== 1) {
return; // another worker owns it
}Process bounded batches: 100 rows, 20 seconds, then reschedule. Record progress after each commit, not only at the end. If execution dies halfway, the next run resumes rather than restarting or duplicating side effects.
External calls need timeouts and circuit breakers
$response = wp_remote_post($url, [
'timeout' => 8,
'headers' => ['Accept' => 'application/json'],
'body' => wp_json_encode($payload),
]);The default timeout is often too generous for a synchronous request and too optimistic for flaky vendor APIs. Treat every remote call as unreliable. Back off exponentially, cap retry counts, preserve the payload for inspection, and surface final failure in wp-admin.
Field notes
- Never put secrets in cron URLs or logs because they end up in access logs.
wp_schedule_event()is recurring by interval; dynamically changing arguments can create duplicate events.- Cache lock keys can help, but database-backed claiming is more reliable across multiple PHP workers.
- Test with two concurrent workers. Single-worker testing hides race conditions that production finds immediately.
Was this lesson helpful?