Separate backend each threads on send_queued_mail#521
Merged
selwin merged 6 commits intoApr 16, 2026
Merged
Conversation
selwin
reviewed
Apr 15, 2026
ibadarrohman
commented
Apr 16, 2026
Comment on lines
+145
to
+147
| Ensure _send_bulk() opens one connection per thread, not one per email. | ||
| With THREADS_PER_PROCESS=1: main thread opens one during prepare, worker | ||
| thread opens one during send — total 2 opens for any number of emails. |
selwin
reviewed
Apr 16, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
LLM Output Claude Sonnet 4.6
Root Cause: In
_send_bulk,prepare_email_message()is called in the main thread before spawning worker threads. This embeds the main thread'sAnymailRequestsBackendconnection (and itsrequests.Session) into every email's_cached_email_message. When theThreadPoolworkers dispatch those emails, all threads concurrently callsession.request()on the same sharedrequests.Session, which is explicitly not thread-safe. This corrupts socket state, causing[Errno 11] Resource temporarily unavailableat the OS level.The fix: in
_send_email, replace the pre-cached connection with a thread-local one fromconnections[]before dispatching. SinceConnectionHandlerusesthreading.local, each worker thread will get its ownAnymailRequestsBackendwith its ownrequests.Session.Deeper Analysis
1. Why
requests.Sessionis not thread-safeA
Sessionobject holds mutable shared state:The critical one is
session.request()itself — it performs a non-atomic read-modify-write sequence:When Thread A and Thread B both call
session.request()at the same time, they both enterprepare_request()andmerge_environment_settings()concurrently — reading and writing the same dict/cookie objects without locks. This is a classic TOCTOU (Time-of-Check-Time-of-Use) race.2. Why does sharing corrupt socket state?
Go one level deeper:
HTTPAdapterowns aurllib3.PoolManager, which maps hostnames →HTTPConnectionPool. Each pool has aqueue.LifoQueueofHTTPConnectionobjects.When 5 threads share the same adapter/pool and all call
adapter.send()simultaneously:All 5 threads simultaneously call
HTTPConnection._new_conn()→socket.create_connection()→ internally callssocket.getaddrinfo()for DNS.At the OS level, DNS resolution requires creating its own temporary UDP socket to query the resolver. Five threads doing this at exactly the same instant means the OS must allocate 5 resolver sockets simultaneously, on top of the 5 TCP sockets being opened. When system resources are tight (file descriptor pressure, socket buffer limits, or the resolver queue is full), the kernel returns EAGAIN on one of those socket allocations.
3. Why specifically Errno 11 (
EAGAIN/Resource temporarily unavailable)EAGAIN(errno 11 on Linux) means: "I can't do this right now — try again later." It's the kernel's way of saying a resource is momentarily exhausted without hard-failing.The exact call that fails, from the traceback:
getaddrinfocreates a non-blocking DNS socket internally. Under the hood, libc's resolver does:So the chain is:
Why per-thread sessions fix it
With the fix, each worker thread calls
connections[alias]which hitsthreading.localstorage. The first access on a given thread creates a brand newAnymailRequestsBackend→ newrequests.Session→ newHTTPAdapter→ newPoolManager. Now:No shared state, no concurrent mutation, sockets are created sequentially within each thread's own connection lifecycle — no
EAGAIN.