Skip to content

Improve FFI multithread performance by using atomics#482

Open
oskirby wants to merge 25 commits into
cloudflare:masterfrom
oskirby:ffi-multithreading
Open

Improve FFI multithread performance by using atomics#482
oskirby wants to merge 25 commits into
cloudflare:masterfrom
oskirby:ffi-multithreading

Conversation

@oskirby
Copy link
Copy Markdown

@oskirby oskirby commented May 26, 2026

I've been trying to make use of the boringtun FFI interface in a multithreaded environment, and I have been finding that the use of a Mutex around the tunnel forces all threads to sequentially access the tunnel structure for every packet encryption and decryption operation.

I find this to be suboptimal given that 99% of the encrypt/decrypt operations don't need to modify the session state at all, and this could be much better done using a RwLock instead. This allows multithreaded access for most packet operations while still acquiring an exclusive lock whenever we need to handle a handshake packet.

To get there, we need to ensure that the odds and ends which do modify counters can still be done race-free, and most of this is simply a matter of using an atomic type instead of a naked counter.

A high level summary of the changes introduced by this PR:

  • Add try_encapsulate() and try_decapsulate() methods that attempt to handle packets without modifying the session state.
  • Convert the C-FFI library to use a RwLock instead of a Mutex
  • Add a benchmark tool to measure FFI performance with multiple threads.
  • Convert the Timers and RateLimiter modules to use AtomicU64 instead of Duration
  • Rewrite the ReceivingKeyCounterValidator to use atomic types and a spinlock.
  • Add a racecheck test to verify that ReceivingKeyCounterValidator is correct in multithreaded environments.

oskirby added 25 commits May 3, 2026 14:39
I think there's another race hiding in will_accept that goes something
like this:

A: Receives packet N
A: Checks counter is good
A: Interrupted
B: Receives packet N+N_BITS
B: Checks counter is good
B: Marks bitmap as received
A: Resumes and find bitmap marked by N+N_BITS

This is a pretty minor race as the packet would be rejected anyways
but we return WireGuardError::DuplicateCounter instead of
WireGuardError::InvalidCounter and that causes the unit test to fail.
@celeste-sinead
Copy link
Copy Markdown
Collaborator

I appreciate the effort here and this sounds like a solid improvement. Unfortunately, I'm unlikely to have the time to give such a large and intrusive change the review attention it needs in order to be merged, anytime in the foreseeable future. This crate is kind of just in bare-minimum maintenance mode at present 😢

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.

2 participants