The failure report is rarely phrased as a race condition. It arrives as: the CRM has two records for one post, or the webhook fired twice and the second one overwrote the first. The log shows two outbound POSTs, both from the same site, both carrying the same payload, seconds apart. Nothing in wp_remote_post() is broken. The problem is where the call lives.
A wp_remote_post() inside a shutdown action is a send-on-any-exit primitive. It is not a send-on-success primitive. If the handler does not know why shutdown fired, it cannot know whether the editorial event it is reporting actually completed. That gap is the race: not inside the HTTP client, but between the logical event and the number of times the handler runs.
Symptom
One editorial action — publishing a post, saving a revision, transitioning a status — produces two outbound requests to the external API. The payloads are identical or near-identical. The API receives them in either order. Downstream, the second write wins, or a duplicate record is created, or a counter increments twice.
The site’s own logs show two entries from the same shutdown handler. If the handler logs an idempotency key, both entries carry the same key. If it logs an entry reason, the two entries often carry different reasons — one from a normal request path, one from a fatal-error path or a second overlapping request. That signature — same key, different entry reason — is the fingerprint of this failure.
Trace: what the shutdown hook actually is
The shutdown action is documented as firing just before PHP shuts down execution. It is called by shutdown_action_hook(), which WordPress registers with PHP via register_shutdown_function() in wp-settings.php (WordPress developer reference: shutdown hook).
The same reference notes that the action is always called — including on fatal errors, Ajax requests, and when exit; or die(); terminates a request. That is the property that makes it useful for logging and the property that makes it dangerous for one-shot outbound sends.
Two consequences follow directly:
- A request that fatals after the editorial event was recorded but before the handler’s success condition was met still reaches shutdown. A handler that assumes “we got here, the work succeeded” will send on a failed request.
- A request that calls
exit;inside another shutdown handler halts the request without running the remaining shutdown handlers (same reference). Ordering between your handler and anything else onshutdownis not something you control from your plugin.
Neither of those is a race in the concurrency sense. They are duplicate-trigger conditions: the same logical event reaches the send path more than once because the send path is attached to an exit hook rather than to the event itself.
Trace: the second overlap source
Core itself now uses shutdown for cron spawning. The wp_cron() reference documents that, as of 6.9, _wp_cron() is moved from wp_loaded to the shutdown action unless ALTERNATE_WP_CRON is enabled (WordPress developer reference: wp_cron()). The same page states plainly that wp_remote_post() does not always respect the timeout and blocking parameters — a timeout of 0.01 may end up taking about a second.
That matters because your handler and core’s cron spawner now share the same hook. A slow outbound POST in your handler can overlap with the cron spawn request, and with the next request’s shutdown handler on a busy site. The HTTP call is the messenger; the shutdown hook is the trigger that can fire more than once per logical event.
Defaults compound the problem. WP_Http::request() sets 'blocking' => true and a default timeout of 5 seconds, filterable via http_request_timeout (WordPress developer reference: WP_Http). A blocking POST with a 5-second ceiling inside a shutdown handler is a request that can outlive the response flush and overlap with whatever else is happening on the box.
Root cause
The handler is attached to the wrong event. It is attached to the end of the request, not to the editorial transition. Any code path that reaches shutdown — normal completion, fatal error, explicit exit, a second overlapping request — runs the handler. The handler has no way to distinguish “the post was published” from “the request that was trying to publish the post died halfway through.”
The remote API cannot be relied on to deduplicate. Even if it could, the ordering problem remains: two sends with the same payload arriving out of order produce a different final state than one send.
So the fix has two parts, and both are required. The send must be idempotent on the sending side, and it must be moved off the shutdown hook onto a bounded, retryable unit of work.
Fix, part one: idempotency on the sending side
Derive a stable key from the editorial event — post ID, revision ID, and action name are sufficient — and write a sent-marker before the POST, not after. If the marker exists, the handler is a no-op. Writing the marker first means a crash between marker-write and POST results in a missed send rather than a duplicate; that is the correct trade for most publishing integrations, because a missed send can be reconciled from the post’s state, while a duplicate cannot be un-sent.
function jv_maybe_send_publish_event( $post_id, $revision_id ) {
$key = sprintf( 'jv_sent_%d_%d_publish', (int) $post_id, (int) $revision_id );
// add_option() returns false when the option already exists.
if ( ! add_option( $key, time(), '', false ) ) {
return; // Already claimed by an earlier invocation.
}
$response = wp_remote_post( 'https://api.example.com/events', array(
'timeout' => 5,
'blocking' => true,
'headers' => array( 'Content-Type' => 'application/json' ),
'body' => wp_json_encode( array(
'post_id' => $post_id,
'revision_id' => $revision_id,
'action' => 'publish',
) ),
) );
if ( is_wp_error( $response ) ) {
// Release the claim so a retry can run.
delete_option( $key );
error_log( sprintf( 'jv send failed key=%s error=%s', $key, $response->get_error_message() ) );
}
}
add_option() is the claim here because it returns false when the option already exists (WordPress developer reference: add_option()). The marker is written before the POST; on failure it is deleted so a retry can claim it again.
Log the key on every invocation, including the no-op path. Two log lines with the same key and different entry reasons is the diagnostic signature described above.
Fix, part two: move the send off shutdown
Schedule a single event with unique arguments and let WP-Cron run the send. The wp_schedule_single_event() reference documents the relevant behavior: an event scheduled within 10 minutes of an existing event with the same hook is ignored unless unique $args are passed, and mismatched $args cause WordPress to treat the event as different, which can lead to duplicate cron events and growth of the cron option (WordPress developer reference: wp_schedule_single_event()).
function jv_schedule_publish_event( $post_id, $revision_id ) {
$args = array( (int) $post_id, (int) $revision_id );
if ( wp_next_scheduled( 'jv_send_publish_event', $args ) ) {
return; // Already queued for this exact event.
}
wp_schedule_single_event( time() + 5, 'jv_send_publish_event', $args );
}
add_action( 'jv_send_publish_event', 'jv_maybe_send_publish_event', 10, 2 );
The 10-minute duplicate rule becomes a feature here: two calls to jv_schedule_publish_event() for the same post and revision within ten minutes collapse to one scheduled event. The wp_next_scheduled() check is belt-and-braces; the unique $args are what actually make the deduplication work.
Note the interaction with the idempotency marker: the scheduled event calls the same jv_maybe_send_publish_event() function, so even if the schedule deduplication fails and two events run, the second is a no-op because the marker is already claimed.
Verification
Three checks, in order of how quickly they catch the failure.
1. Confirm the handler is no longer on shutdown.
wp eval 'global $wp_filter; var_dump( isset( $wp_filter["shutdown"] ) ? array_keys( $wp_filter["shutdown"]->callbacks ) : array() );'
Your handler’s callback should not appear. If it does, something else re-registered it.
2. Confirm the marker is written before the POST. Query the options table for the key after a publish:
wp db query "SELECT option_name, option_value FROM $(wp db prefix --allow-root)options WHERE option_name LIKE 'jv_sent_%' ORDER BY option_id DESC LIMIT 5;"
The option_value is the timestamp of the claim. If the row exists and the API received the payload, the ordering is correct. If the row exists and the API did not receive the payload, the send failed after the claim — check the error log for the jv send failed line and confirm the claim was released.
3. Compare API-side receipt timestamps against request IDs. If the external API exposes a request ID or receipt timestamp, correlate it with the jv_sent_ option timestamp. A single claim timestamp with two API receipts means the remote side duplicated the request; a single claim timestamp with one receipt means the fix is working. Two claim timestamps for the same post and revision means the marker is not being written atomically — check that add_option() is being called before the POST and not after.
What this is not
This is not a bug in wp_remote_post(). The function performs an HTTP request using the POST method and returns the response or a WP_Error (WordPress developer reference: wp_remote_post()). It does what it says. The failure is in the placement of the call and the absence of an idempotency claim around it.
It is also not a problem that a filter on pre_http_request or a constant like WP_HTTP_BLOCK_EXTERNAL will solve. Those short-circuit the request; they do not change how many times the handler runs. A blocked request still consumes the shutdown slot and still logs an entry.
FAQ
Can I just add a transient check around the POST? You can, but a transient is not atomic. Two concurrent requests can both read the transient as absent and both proceed. add_option() returns false when the option exists; use it for the claim, and use a transient only for non-critical caching.
Why not use wp_schedule_single_event() alone and skip the marker? Because the schedule deduplication window is ten minutes and is keyed on exact $args. A retry after ten minutes, or a call with slightly different arguments, will schedule a second event. The marker is the backstop that makes the send idempotent regardless of how many times the event is scheduled.
Does this apply to wp_safe_remote_post() too? Yes. The safe variant adds URL validation; it does not change the shutdown-hook mechanics or the duplicate-trigger conditions.
What if the external API requires a response before the request ends? Then a blocking POST inside shutdown is the wrong shape entirely. Move the send to a scheduled event and let the API’s own retry or webhook mechanism handle delivery confirmation. The shutdown hook is not a delivery guarantee.
How do I know the shutdown handler fired on a fatal error rather than a normal request? Log error_get_last() at the top of the handler. On a normal request it returns null; on a fatal-error path it returns the error array. That is the entry-reason log line referenced above.
If you are still diagnosing why a fresh install is returning empty results before you get to outbound integrations, the first-fix checklist for a new WordPress site that says nothing found covers the query and rewrite layer that sits underneath this one.