How to Add a Progress Indicator to Drupal Long-Running Processes
Long-running Drupal processes include bulk content imports, media conversions, search reindexing and synchronising records with external systems. A browser request that waits for PHP to finish can hit gateway limits, leaving editors staring at a blank screen while work continues on the server. Adding a progress indicator to Drupal long-running processes starts with separating the background work from the page request.
The durable pattern is to create a job, persist its status, expose a small authenticated JSON endpoint and let the interface poll that endpoint. Drupal’s Batch API can suit shorter interactive operations, while Queue API with cron or a dedicated worker handles imports that may run for minutes or hours. The interface can then report real progress rather than using animation to pretend a task is nearly finished.
Choose feedback that matches the job
Choose feedback according to whether the total amount of work is known. A percentage is meaningful for records or files with a countable total. Duration-based work often works better with phases such as “checking files”, “processing images” and “saving results”.
Keep the message specific and honest. “Hang tight—we’re still processing records” may suit an internal Australian team, but it should accompany an accessible status value rather than replace one. Never advance a bar on a timer unless the timer represents measured work.
| Feedback pattern | Best suited to | Strength | Limitation |
|---|---|---|---|
| Determinate progress bar | Work with a known unit count | Shows a meaningful percentage | The total may change during processing |
| Indeterminate spinner | Work of unknown duration | Simple and familiar | Offers no completion estimate |
| Phase list | Multi-stage operations | Explains what the worker is doing | Requires more implementation work |
| Background status panel | Queued or external jobs | Can survive navigation and refreshes | Needs a persisted job identifier |
A queued job also needs a way to recover its state after navigation or refresh. That requirement makes a background status panel more suitable than a short-lived spinner that exists only inside one page.
Model progress as durable job state
Create a job record as soon as the editor starts the operation. Give it an unguessable identifier and record the owning user ID, status, current unit, total units, phase, message, creation time, update time and error details. Typical states are pending, running, completed and failed.
For shorter imports triggered by a form, Drupal’s Batch API can provide a built-in progress sequence. For work that must survive a slow gateway, use Queue API and keep the status record separately. For a modest number of jobs, the State API can hold one keyed record such as import_job.<uuid>. Do not treat cache as the source of truth because cached entries may disappear before the worker finishes. A custom entity or database table is a better fit for high volume, reporting, indexed job queues or formal retention rules.
Update the record after each processed chunk. Calculate the percentage from current / total, clamp it to 0–100 and leave the percentage empty when the total is unknown. Timestamps should be stored in UTC, while the interface can convert them for display. A worker should also record a correlation ID so support staff can trace a failed job through Drupal logs without exposing internal details to the browser.
Expose status with a secure Drupal endpoint
Expose status through a read-only Drupal route such as /api/import-progress/{job_id}. The controller must load the job, confirm that the current user owns it or has an administrative permission, and return only the fields required by the interface. Treat the identifier as unguessable, not as authorisation; ownership checks are still required.
public function status(string $jobId): JsonResponse
{
$job = \Drupal::state()->get('import_job.' . $jobId);
$uid = (int) \Drupal::currentUser()->id();
if (!$job || (($job['uid'] ?? 0) !== $uid
&& !\Drupal::currentUser()->hasPermission('administer import jobs'))) {
throw new AccessDeniedHttpException();
}
$total = (int) ($job['total'] ?? 0);
$current = (int) ($job['current'] ?? 0);
$response = new JsonResponse([
'status' => $job['status'],
'phase' => $job['phase'],
'current' => $current,
'total' => $total,
'percent' => $total > 0
? (int) floor(($current / $total) * 100)
: null,
'message' => $job['message'],
]);
$response->headers->addCacheControlDirective('no-store');
return $response;
}
On the client, poll every two to five seconds with fetch or Drupal’s AJAX layer. Apply exponential backoff after network failures and avoid creating a second timer while one is already running. A failed poll should display “Connection interrupted—retrying” rather than changing the job to failed. The status request is read-only, so it does not need a CSRF token; commands that start, retry or cancel work must use Drupal’s CSRF protection.
Build accessible progress feedback
Use semantic markup for the indicator rather than a collection of styled div elements. The server-generated URL should sit in a data attribute or drupalSettings so the template remains independent of a particular environment.
<div class="job-progress"
data-job-status-url="/api/import-progress/8f3c2b10-4e89-4f7a-a7c2-91d506e53f2d"
aria-busy="true">
<label for="import-progress">Import progress</label>
<progress id="import-progress" max="100" value="0">0%</progress>
<p data-job-message role="status" aria-live="polite">
Preparing the import…
</p>
</div>
JavaScript should set the value attribute and visible percentage from the server response, not calculate a decorative animation. For an unknown total, remove the value so the native progress element remains indeterminate. Update the accompanying text at sensible thresholds, and use aria-busy while the request is active.
Keep announcements calm. A live region that repeats every two seconds can flood a screen reader, so announce major phases, completion and failure rather than every percentage. Never rely on colour alone to communicate state, and respect prefers-reduced-motion for any spinner. Add the JavaScript through a Drupal library and pass the status URL in drupalSettings or a data attribute so themes and deployment environments can change it.
Handle retries, completion and refreshes
A transient network drop should not discard a job. Keep the last known state, pause briefly and then retry with backoff. If the editor refreshes the page, store the job ID in the server-side session or include it in a signed return route, then rebuild the progress component from the endpoint.
On completion, replace the form or progress region with the result and release the client-side polling timer. On failure, show a safe summary such as “120 of 2,400 records processed”; keep stack traces and command output in restricted logs. A retry should resume from a checkpoint or create an idempotent new attempt, never silently duplicate imports.
Cancellation needs a separate authorised command because the status endpoint cannot safely mutate a job. If cancellation is supported, let the worker stop at the next checkpoint and report cancelled as a terminal state. Define a server-side timeout so abandoned jobs do not occupy a queue worker indefinitely.
Scale safely across Australian environments
Run work through Queue API and protect it with a lock or an atomic lease. Configure cron regularly, and use a dedicated worker such as drush queue:worker when traffic or import volume justifies it. Retries are normal, so every processing step must be idempotent: use stable record keys, record what completed and avoid applying the same update twice.
Australian deployments often connect teams in Sydney, Melbourne and Brisbane with users at regional sites such as Toowoomba. Websocket-only progress can fail when mobile coverage drops, whereas polling with backoff and durable server state continues to recover. A final status can remain visible for a short period, but plan proper cleanup so old job records do not accumulate.
Public-sector, education and enterprise buyers in Australia commonly ask for WCAG 2.1 or 2.2 AA conformance, security review and privacy assessment. Keep the progress response free of personal data, and check whether the Australian Privacy Act applies to the imported records. For project-specific Drupal implementation guidance, compare the pattern with the site’s existing access-control and deployment conventions.
Use Australian English such as “optimise” and “behaviour”, and keep internal copy direct without becoming overly casual. Store timestamps in UTC but label displayed times with the relevant Australian zone, including AEST/AEDT daylight changes and ACST/AWST where those regions are involved. This avoids confusion during Brisbane–Melbourne operational handoffs.
Practical rollout recommendations
Roll the feature out with production-sized sample data and make each operational choice explicit before release. These checks keep the implementation useful when imports are routine in one site and unusual in another.
- Benchmark a full import and establish whether the total count is stable enough for a percentage.
- Expose meaningful phases and record progress after each durable unit of work.
- Enforce ownership checks, route permissions, no-store caching and safe error messages.
- Test slow networks, worker failures, duplicate requests, refreshes, cancellation and screen-reader operation.
- Monitor queue depth, processing duration, timeout rates and the correlation IDs attached to failed jobs.
Release the change to a small group of trusted editors before expanding its use. Keep a runbook covering stuck workers, retries, timeouts and manual cleanup. With durable state, authenticated polling and accessible feedback, the indicator remains useful whether the task finishes in seconds or runs overnight.