All writing

Telling the page why a long-running download failed

The setup here is a Java servlet app (Spring MVC on Tomcat) with a React component library on top, and a reporting page that can ask the server to export the whole report as CSV, XLS or PDF. Most of what I learned while changing how that export reports its outcome came before any code was written, so this is mostly about the designs that didn’t make it and why, with a few things the running version showed at the end.

How the outcome used to travel

The export runs a query on the server with a timeout, and when the query takes too long the server doesn’t fail the request. Instead it puts a flag in the server session, something like “the last export was cancelled as long running”, and redirects to the report page. The next time that page loads its grid it finds the flag and shows a dialog that offers to schedule the report to run in the background. Errors went the same way, as an error message parked in the session for whichever page asked next.

That works as long as the export is a normal browser navigation, because the browser follows the redirect, the page reloads and the next load is the right one. The newer React page doesn’t navigate though, it fetches the file with an XHR (responseType: 'blob') and saves whatever comes back. When I reproduced a long-running export on a test environment, the XHR followed the redirect and got a 200 with the app’s HTML shell as the body, which the page took as the file (it would have been saved as report.csv), with no dialog and no error. The flag was still sitting in the session, so when I later opened a completely different report in the same tab, the “long running report” dialog popped up on it straight away, offering to schedule a report I never exported.

So the goal was simple to state, the page that started the export should learn the outcome from its own request, and that request shouldn’t leave anything in the session for someone else to find.

The first design, a hidden iframe

My first idea was to keep the export a native download, because native downloads have nice properties, the browser shows its own progress and the file goes straight to disk. The usual trick is a hidden iframe pointed at the export URL, plus a token the page sends along, and the server sets a cookie named after that token with the outcome, which the page polls for.

Before writing it up properly I had a few agent reviewers go through the design against the real code, and the biggest problem they found was in how the app keeps its server-side state. The server keeps state per browser tab, and a request coming from a hidden frame doesn’t land in the tab’s state, so the export would run against a state that doesn’t have the user’s current search in it. The design had a routing exception for that, but against a server that didn’t have the exception yet (front end and back end deploy independently, so that combination is something the design has to handle) the page would get a file built from the wrong data and call it a success. Add a few paths where no cookie ever arrives and the page stays busy forever, and the native download stopped looking worth it. The other option on the table, writing the file to server storage and handing the page a link after a JSON answer, would have written every export twice and kept customer data on the server until something cleaned it up, so that one never got far either.

The second design, an XHR that asks for JSON

The simpler version is to keep the XHR and let it opt in with a request header, something like X-Want-Outcome: json. A request with the header gets the file when the export works, and a small JSON body ({"status":"timeout"} or {"status":"failed"}) when it doesn’t, and a request without it gets the old redirect. An XHR ends in load or error whichever way the server finishes, and it already runs in the tab’s own server state (the repro showed that). The page has to check the Content-Type of a 200 before treating the blob as a file, since the HTML shell also comes back as a 200, and read the JSON out of the blob with await blob.text() when it isn’t one. Against an older server that ignores the header, the long-running case then shows as an error instead of a saved HTML page, but the old server still parks the flag in the session, and a couple of its failures can still produce a damaged file, so the server side has to ship first.

I wanted this on the legacy report page too, and the second round of reviews talked me out of it. That page uses a native download today, and moving it to an XHR would cost it the download progress and the ability to survive navigation, and the page would have to save the blob itself, through an old global click handler that drops quick repeated link clicks. So the scope got narrowed to the React page, and the legacy page keeps the redirect for now, which is fine because the redirect works there.

The React page pays those costs too, but it was already downloading through an XHR, so nothing got worse there. Once it was built, an export of a few hundred megabytes of CSV (much smaller compressed on the wire) and a mid-sized XLSX came through the opt-in path the same size as without it. The page’s JS heap didn’t grow, which says less than it seems to, because a Blob’s data isn’t in the JS heap at all, the browser holds it (and can spill it to disk), so the heap numbers simply don’t show that memory. I didn’t measure the browser’s own memory for it, so if that’s the number you care about, look at the browser’s task manager rather than a heap snapshot.

Aborting a file that is already half sent

A harder servlet problem shows up once the server has started sending the file. Before anything is flushed we can still throw the body away and answer with JSON, but CSV exports flush in chunks, so a failure after the first chunk happens on a response that is already committed with a 200. If the server then ends the response normally, the browser gets a cut-off CSV and the page saves it as a complete file, which is the worst outcome of all of them.

The plan was to rethrow from the controller and let the exception reach Tomcat, which can’t send an error page on a committed response and closes the connection instead, without the final chunk on HTTP/1.1, so the XHR fails. Then a review of the app’s filters turned up an error-handling filter in front of every request that logged exceptions and then let the response finish normally, which is not unusual in older servlet apps, and which meant the response would have ended cleanly anyway. The fix there is a narrow carve-out, rethrowing only for requests that opted in and only when the response is already committed:

} catch (Exception e) {
    // Opted-in exports read their outcome from the response; a committed
    // failure must reach the container so it aborts instead of ending cleanly.
    // The controller has already logged it.
    if (ExportOptIn.isSet(request) && response.isCommitted()) {
        throw e;
    }
    log.error("Request failed", e);
}

The throw e; compiles because doFilter already declares IOException and ServletException and Java’s precise rethrow knows the try body can’t throw anything else checked. The marker is a request attribute that the controller sets after it has checked the action is one of the report exports, not the raw header. A filter in front of every request that trusts a client header would change error handling for any URL a client feels like sending it to, while the attribute only exists where our own code decided it should.

Streams that close themselves

The PDF and CSV exports had the same kind of problem one level down. The PDF wrote through try-with-resources:

try (OutputStream out = new BufferedOutputStream(response.getOutputStream())) {
    pdfGenerator.generate(document, out);
}

When generate throws halfway, the unwind closes out, and closing the servlet output stream ends the response, so by the time any rethrow reaches the filter the truncated PDF has already gone out as a complete 200. The CSV writer was opened the same way. For CSV, on the opt-in path, the fix is to not close the servlet stream on the failure path at all (only on success), so the exception reaches the container with the response still open and the abort above can happen. CSV writes rows as it reads them, so unlike the PDF there’s no finished document to render first. The PDF, on the opt-in path, is rendered into a ByteArrayOutputStream first and copied to the response only after generate returns, which is affordable because the PDF export is already capped at a row count, and that cap is what bounds the memory each request holds on the server (so it isn’t a pattern to copy for an export without one). Every PDF generator failure then happens before commit, where a JSON error still works.

What the plan review simplified

By this point the design had grown a request-scoped outcome object, a response wrapper that tracked whether any body bytes went out, and per-export rules for when to rethrow. A plan review pointed out that most of that was redundant, because the export actions already return a status, and with the swallowed failures fixed every failure returns something other than success. So the action’s returned status is the outcome, where success means the file, the long-running constant means the timeout JSON, anything else means the failure JSON, and if the response is committed and the status isn’t success, the controller throws. That’s one rule in one place instead of four.

Small servlet details

  • response.resetBuffer() drops the unsent body and keeps headers and cookies, while response.reset() also drops cookies that earlier filters set (a session or anti-forgery cookie, say), so the browser never gets them while the server assumes it did. resetBuffer() only works before commit (it throws IllegalStateException after) and leaves the status alone, so set the status and overwrite Content-Type and Content-Disposition (to inline) yourself.
  • setHeader(name, null) does nothing on Tomcat 9 and removes the header on Tomcat 11, which matters when the code is compiled against one and run on the other. I first had this from reading the sources, and a small probe against Tomcat’s Response class from both versions showed the same thing, and the same probe on Tomcat 9 confirmed the reset() cookie point above. The servlet API has no removeHeader, so if the code has to behave the same on both, overwrite headers instead of nulling them.

The abort after commit was the part I trusted least, since it rests on what the container does with an exception it gets too late. To check it, a throwaway branch on the opt-in CSV path wrote one row, committed the response and then threw, and through the HTTP/2 proxy in front of the app (which turns the dropped connection into a reset stream) Chrome’s blob XHR ended with an error event and status 0 after a few bytes, so nothing was saved, while a control request on the same report got the whole file. I only ran it in Chrome, so Firefox and Safari are still an assumption.

The outcome of a request belongs in that request’s response, and the session is the wrong place for it because whoever reads the session next is not necessarily whoever asked. Moving it there sounded like a small change and it mostly is, but each design ran into something about the container that the obvious version didn’t account for, and none of it was visible from the design doc, it all came from reading the actual filter and export code. Anything that depends on when a servlet response commits has to be checked against whatever sits between the code and the container catching exceptions, and against every place that closes the output stream.

Email address copied [email protected]