Skip to content

⚡ Bolt: Offload synchronous API operations to worker threads#340

Open
anchapin wants to merge 2 commits into
mainfrom
bolt-fastapi-anyio-offload-2885066603634316720
Open

⚡ Bolt: Offload synchronous API operations to worker threads#340
anchapin wants to merge 2 commits into
mainfrom
bolt-fastapi-anyio-offload-2885066603634316720

Conversation

@anchapin

@anchapin anchapin commented Jun 5, 2026

Copy link
Copy Markdown
Owner

💡 What: We wrapped heavy blocking synchronous operations (such as file reading/writing, PDF compilation, and heavy string processing) within the FastAPI route handlers (api/main.py) using anyio.to_thread.run_sync and functools.partial.
🎯 Why: FastAPI uses an asyncio event loop. Running long blocking, synchronous functions inside async def routes stalls the event loop, causing request starvation and severely limiting the concurrency and throughput of the API server. Offloading them to a worker thread pool keeps the main loop responsive.
📊 Impact: Eliminates main thread blocking during I/O and PDF compilations, dramatically increasing server concurrency and throughput under load.
🔬 Measurement: The test suite passes fully, and the endpoints continue to behave as expected. You can verify the behavior by sending concurrent requests to the /v1/render/pdf or /v1/cover-letter endpoints and noting the improved handling compared to sequential blocking processing.


PR created automatically by Jules for task 2885066603634316720 started by @anchapin

Summary by Sourcery

Offload blocking file I/O, PDF generation, and heavy synchronous processing in FastAPI endpoints to background worker threads to prevent event loop starvation and improve concurrency.

Enhancements:

  • Wrap PDF generation, tailoring, ATS report generation, cover letter generation, JSON resume conversion, and related file operations in anyio.to_thread.run_sync to run them in worker threads.
  • Adjust PDF existence checks and file read/write operations to execute asynchronously via worker threads while preserving existing API behavior.
  • Document the performance lesson and best practice for offloading synchronous operations in FastAPI within .jules/bolt.md.

- Imported `anyio` and `functools.partial` in `api/main.py`.
- Wrapped heavy blocking operations (`generator.generate`, `output_pdf.read_bytes`, `yaml.dump`, `converter.json_resume_to_yaml`, `generator.tailor_data`, `generator.generate_report`, and `generator._compile_pdf`) using `anyio.to_thread.run_sync`.
- This ensures the FastAPI event loop is not starved by synchronous IO and PDF compilation processes.

Co-authored-by: anchapin <6326294+anchapin@users.noreply.github.com>
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@sourcery-ai

sourcery-ai Bot commented Jun 5, 2026

Copy link
Copy Markdown

Reviewer's Guide

Offloads blocking PDF generation, file I/O, and heavy synchronous processing in FastAPI routes to worker threads using anyio.to_thread.run_sync and functools.partial, and documents the pattern in the Bolt guide.

Sequence diagram for offloading PDF rendering to worker threads

sequenceDiagram
    actor Client
    participant FastAPI_render_pdf as FastAPI_render_pdf
    participant anyio_to_thread as anyio_to_thread_run_sync
    participant TemplateGenerator as TemplateGenerator_generate
    participant FileSystem

    Client->>FastAPI_render_pdf: render_pdf(request)
    FastAPI_render_pdf->>anyio_to_thread: run_sync(partial(generator.generate,...))
    anyio_to_thread->>TemplateGenerator: generate(variant, output_format, output_path)
    TemplateGenerator->>FileSystem: write_pdf(output_path)
    FileSystem-->>TemplateGenerator: pdf_written

    FastAPI_render_pdf->>anyio_to_thread: run_sync(output_pdf.exists)
    anyio_to_thread-->>FastAPI_render_pdf: exists()

    FastAPI_render_pdf->>anyio_to_thread: run_sync(output_pdf.read_bytes)
    anyio_to_thread->>FileSystem: read_bytes(output_path)
    FileSystem-->>anyio_to_thread: pdf_bytes
    anyio_to_thread-->>FastAPI_render_pdf: pdf_bytes

    FastAPI_render_pdf-->>Client: Response(content=pdf_bytes)
Loading

File-Level Changes

Change Details Files
Offload synchronous PDF generation and file I/O in render_pdf and render_resume_pdf routes to worker threads.
  • Wrap generator.generate calls in anyio.to_thread.run_sync via functools.partial to move PDF compilation off the event loop.
  • Wrap Path.exists and Path.read_bytes calls in anyio.to_thread.run_sync to avoid blocking on file existence checks and reads.
  • Introduce small helper closures where needed to perform file writes/reads inside run_sync for YAML and PDF files.
api/main.py
Offload synchronous AI/generator operations in resume tailoring, ATS checks, and cover letter generation to worker threads.
  • Wrap generator.tailor_data, generator.generate_report, and generator.generate_non_interactive calls in anyio.to_thread.run_sync via functools.partial.
  • Ensure returned structured data (e.g., tailored resumes, ATS reports, cover-letter outputs) is obtained asynchronously without blocking the event loop.
api/main.py
Offload JSON Resume to YAML conversion from FastAPI handlers to worker threads.
  • Wrap JSONResumeConverter.json_resume_to_yaml calls in anyio.to_thread.run_sync via functools.partial in both create_resume and render_resume_pdf routes.
  • Ensure YAML dumping to disk is performed via a helper function executed in run_sync to prevent blocking writes on the event loop.
api/main.py
Document the offloading pattern and rationale in the Bolt performance guide.
  • Add a Bolt note describing event loop starvation caused by synchronous file I/O and PDF compilation in FastAPI.
  • Document the standard pattern of using anyio.to_thread.run_sync with functools.partial for blocking operations, including the need for partial when passing keyword arguments.
.jules/bolt.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've left some high level feedback:

  • Several places (e.g., render_pdf, render_resume_pdf) now call anyio.to_thread.run_sync multiple times in a row on the same path (exists, read_bytes); consider wrapping the combined logic in a single helper function so it runs in one thread invocation and avoids repeated context switching overhead.
  • The ad-hoc inline helpers like _read_pdf and _write_yaml are duplicated patterns for file I/O; extracting shared, well-named utility functions for common read/write operations would make the threading strategy clearer and reduce repetition.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Several places (e.g., `render_pdf`, `render_resume_pdf`) now call `anyio.to_thread.run_sync` multiple times in a row on the same path (`exists`, `read_bytes`); consider wrapping the combined logic in a single helper function so it runs in one thread invocation and avoids repeated context switching overhead.
- The ad-hoc inline helpers like `_read_pdf` and `_write_yaml` are duplicated patterns for file I/O; extracting shared, well-named utility functions for common read/write operations would make the threading strategy clearer and reduce repetition.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

- Converted `async def` routes to `def` in `api/main.py`.
- This ensures FastAPI automatically runs these routes in an external threadpool, preventing the `asyncio` event loop from being starved by synchronous I/O and PDF compilation processes.
- This change maintains complete readability without needing manual `anyio.to_thread` wrappers.

Co-authored-by: anchapin <6326294+anchapin@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant