In short
- The problem: long tasks in an admin, like exporting orders, importing products or bulk-editing prices, run in the background, but the screen usually shows a spinner that cannot tell "working" from "stuck" or "failed". Staff click the button again, close the tab, or file a support ticket, and sometimes the job runs twice.
- What I do about it: I give every long task a job record on the server with a small set of explicit states, have the UI poll that record instead of waiting on one request, make retries safe to repeat, and show progress, failure and partial results in plain words.
- Who this is for: engineers building React admin panels on Laravel or WordPress backends, and leads who keep hearing "the export is broken" when it is not.
A typical version of this looks like this. A store manager clicks "Export last year's orders". The button turns into a spinner. Forty seconds later the request times out at the proxy, the spinner turns into "Something went wrong", and the manager clicks again. On the server, the first export was still running fine. Now two are running, both writing the same file, and the database is busier than it was a minute ago.
Nothing in that story is a crash. The server did its job. The failure is that the interface tied a five-minute task to a single HTTP request and then reported the request's death as the task's death. The manager made a reasonable decision based on a screen that was wrong.
I wrote about the backend half of this, moving long work out of the request, in Laravel queues beside WordPress. This post is the other half: what the React admin should do once the work is on a queue.
A long task needs a job record, not a long request
The fix starts on the server. The button should not do the work; it should ask for the work to be done and get back a receipt. In HTTP terms, that means responding 202 Accepted with an ID the client can check later, instead of holding the connection open until the export finishes.
In Laravel, that is a controller that creates a row and dispatches a job:
public function store(StartExportRequest $request): JsonResponse
{
$run = JobRun::create([
'type' => 'orders_export',
'status' => 'queued',
'user_id' => $request->user()->id,
'params' => $request->validated(),
'idempotency_key' => $request->header('Idempotency-Key'),
]);
ExportOrders::dispatch($run->id);
return response()->json(['id' => $run->id, 'status' => 'queued'], 202);
}
The job updates that row as it goes: running when it starts, a processed count every few hundred rows, succeeded with a download URL, or failed with a message a human can read. Laravel's job batching can carry some of this for you, since a batch exposes totalJobs, pendingJobs, failedJobs, progress() and finished(). I still keep my own small table, because the admin needs things a batch does not know about: who started it, what filters they chose, and where the result file lives.
On WordPress, the same shape works with Action Scheduler doing the queue work and a custom table or post type holding the job record. The storage changes; the contract with the UI does not.
Five explicit states beat one boolean
Most broken job UIs have an isLoading flag and nothing else. A background task needs more than that, and the states should be the same words on the server and in TypeScript:
type JobStatus = 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled';
interface JobRun {
id: number;
type: string;
status: JobStatus;
processed: number;
total: number | null; // null when the job can't know yet
error: string | null; // written for staff, not a stack trace
resultUrl: string | null;
updatedAt: string;
}
Two details matter more than they look. total is nullable because many jobs cannot know their size up front, and a fake progress bar is worse than an honest "1,240 rows so far". And updatedAt lets the UI notice a job that says running but has not changed in a long time, which is how you tell "slow" from "dead worker" without guessing.
I keep partial success as data, not a sixth status. An import that saved 4,900 rows and rejected 100 is succeeded with a list of rejected rows attached. Calling that a failure makes staff redo work that already happened.
Poll the job, and stop when it is done
With a job ID in hand, the React side is a query that refetches on an interval and turns itself off once the job reaches a final state. In TanStack Query v5, refetchInterval can be a function that receives the query, so the interval can depend on the latest data:
const FINAL: JobStatus[] = ['succeeded', 'failed', 'cancelled'];
function useJobRun(id: number | null) {
return useQuery({
queryKey: ['job-runs', id],
queryFn: () => api.getJobRun(id!),
enabled: id !== null,
refetchInterval: (query) => {
const job = query.state.data;
if (!job || FINAL.includes(job.status)) return false;
return job.status === 'queued' ? 5000 : 2000;
},
});
}
Polling every two to five seconds is plenty for an export. I reach for WebSockets or server-sent events only when many people watch the same job, or the job is short enough that a five-second lag feels broken. For most back offices, polling is simpler to run, works through every proxy, and survives a laptop going to sleep.
By default, TanStack Query pauses interval refetching while the tab is in the background (refetchIntervalInBackground is false). I leave that alone. The job keeps running on the server either way; the tab only needs to catch up when someone looks at it.
The job must outlive the page
The first version of most job UIs stores the job ID in component state. Then someone refreshes the page, the ID is gone, and the export they started is invisible even though it is still running.
I list a user's recent jobs from the server instead: a small "Recent exports" panel, or a tray in the admin header, fed by an endpoint like GET /job-runs?mine=1&recent=1. The page that started the job highlights it, but any page can show it. This also answers the question support hears most often, "did my import go through?", without anyone opening a database console.
The same panel is where finished files live. A download link that only appears in a toast for five seconds is a link most people miss.
Retries are only safe if the server makes them safe
There are two kinds of retry in this flow, and they need different protections.
The user retrying the start. Double clicks, flaky Wi-Fi, a timeout on the start request itself. The client sends an idempotency key, a random ID generated once when the user clicks, and the server returns the existing job if it has already seen that key. I also disable the start button while the start request is in flight and while the same user has an identical job queued or running. The button guards the common case; the key guards the rest.
The queue retrying the work. Laravel will rerun a failed job up to its $tries limit, with whatever backoff you set. That is only safe if the job can run twice without doing damage. For an export, that means writing to a temporary file and moving it into place at the end. For an import or bulk edit, it means tracking which rows are done, or making each row's write an upsert keyed on something stable, so a second attempt picks up where the first stopped instead of starting over.
The UI's part is to tell the truth about it. If the server reports "attempt 2 of 3", showing "Retrying after a temporary error" is better than a progress bar that silently jumps back to zero.
Failure messages are written for the person who clicked
A failed job should say what happened, what was kept, and what to do next. "Export failed" is not that. "The export stopped after 12,000 of 30,000 orders because the database connection was lost. Nothing was charged or changed. Try again; it will start from the beginning" is.
That means the job writes a human message to error and logs the stack trace separately. The UI shows the message, a "Try again" button that creates a new job with the same parameters, and a reference ID support can search for. For imports, I also offer the rejected rows as a downloadable file, because "row 1,482 has an invalid SKU" is something a store manager can fix in a spreadsheet in two minutes.
Cancellation deserves the same honesty. If cancelling only stops the job at the next chunk, the button should say "Stopping..." until the server confirms cancelled, not pretend it stopped instantly. This is the same rule I use for optimistic updates in a React admin: show pending as pending until the server agrees.
Trade-offs: when this is too much
This pattern has real cost: a table, a status endpoint, a polling hook, a recent-jobs panel, and the discipline to keep job states accurate. It is not always worth it.
- Short tasks don't need it. If the work reliably finishes in a second or two, a normal request with a clear loading state is simpler and more honest. I start considering a job record when a task can take longer than a typical proxy or PHP timeout, or when it touches thousands of rows.
- Progress counts can cost more than they're worth. Writing progress to the database after every row on a large import adds load to the same database the import is hitting. Update every few hundred rows, or on a timer, and accept a slightly jumpy bar.
- Polling doesn't scale to everyone watching everything. If a dashboard polls dozens of jobs for hundreds of users, the status endpoint becomes a hot path. At that point, server-sent events or a push channel earn their complexity. Most admins never reach that point.
- One job table for everything can turn into a junk drawer. Keep the shared fields small (status, counts, error, result) and put job-specific details in a typed
paramsorresultcolumn rather than adding a column for every new job type.
What I check on a project like this
- Does every task that can outlast a request timeout return a job ID instead of doing the work inline?
- Are job states explicit and shared between the backend and the TypeScript types, with partial success represented as data?
- Does the polling stop when a job reaches a final state, and does the UI notice a
runningjob that has not updated in a long time? - Can a user find a job they started after a refresh or from another page?
- Is starting a job protected against double submits with an idempotency key, not just a disabled button?
- Can every queued job run twice without duplicating rows, files or side effects?
- Do failure messages say what happened, what was kept and what to do next, with a reference ID for support?
- Does cancel show "Stopping..." until the server confirms it?
Background jobs are not hard to start; they are hard to explain to the person waiting on them. The work I put in is mostly on that explanation: a job record the server owns, a handful of states that mean the same thing everywhere, polling that stops when it should, retries that cannot double the damage, and messages a store manager can act on. Get those right and the support tickets about "broken" exports mostly disappear, because the screen finally says what the server already knew.