Skip to content

TCP.listen_shared lets N processes share a port; TCP.listen keeps owning its own - #972

Closed
aldeni wants to merge 3 commits into
bendlang:mainfrom
aldeni:tcp-listen-reuseport
Closed

aldeni wants to merge 3 commits into
bendlang:mainfrom
aldeni:tcp-listen-reuseport

Conversation

@aldeni

@aldeni aldeni commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

What changes

  • TCP.listen_shared(port), new in bend2/base.bend: a listener with SO_REUSEPORT set before the bind, so N processes that all call it share one port. If the option is refused, the call fails (ENOPROTOOPT where the platform lacks it) instead of quietly owning the port.
  • TCP.listen is as it was before this PR: SO_REUSEADDR only, so a second listener on its port fails with EADDRINUSE.
  • Both defs share bend2/effs/tcp_listen.c and .js; each effect sits under its own CID_* guard, as in file_read.c.
  • guide/GUIDE.md: what each call does; on Linux the kernel spreads accepted connections over the sharers, on macOS the bind is permitted but the first listener takes every connection.
  • tests/io/tcp_listen_shared.bend: probes a port upward from 19947 with TCP.listen_shared, shares it twice, and pins that a plain TCP.listen on it answers Address already in use.

Why

Bend's IO loop is one per process -- threads only run spawned ! work -- so the only way a lightweight route uses N cores is N processes on one port. Measured on one 4-core machine, same light route, same client: one Bend process with 4 threads serves 88.3k req/s; a second Bend process on the same port cannot start; Bun with 4 processes on one port (reusePort: true) serves 118.9k.

Why opt-in

The first version of this PR set SO_REUSEPORT in TCP.listen by default and argued nothing would regress, since no test asserted that a second listen fails. Review showed that was wrong: tcp_listen_any, in the TCP tests, finds a free port by a TCP.listen that fails, so concurrent copies of those tests shared ports and accepted each other's clients (@nicolas-abril, on macOS). Reproduced on Linux x86-64, four concurrent copies of each test, three rounds, native lane:

test base default-on this PR
tcp_loopback 12/12 8/12 12/12
tcp_short_recv 12/12 11/12 12/12
tcp_spawn 12/12 8/12 12/12
tcp_poll 12/12 10/12 12/12

Beyond the tests, default-on turns a loud mistake into a silent one: on Linux an accidental second instance splits traffic with the first; on macOS it starts and never receives a connection (@nicolas-abril, @paulovitin). Opt-in keeps EADDRINUSE as the default on both, and puts the Linux-only benefit behind a name that says what it does -- the shape Bun (reusePort: true) and Node 23.1+ (net.listen({reusePort: true})) already use.

Test output

tests/io/tcp_listen_shared.bend, in the check, interpreted, JS-built and C-built lanes (this repo's bend2/main.ts via bun), prints:

shared
shared again
Address already in use

It also passes with four concurrent copies. Negative check: with TCP.listen made shared again, the third line becomes plain listen shared the port.

The existing tcp_loopback, tcp_short_recv, tcp_spawn, tcp_poll and tcp_send_slow_peer pass in the interpreted, JS and native lanes, and the table above was rerun on this PR's head. This PR applies on 2.0.26 and together with #977 and #978 in any order.

Not tested here: macOS (no machine; the guide's macOS sentence rests on the two reviewers' measurements), and the cluster-backed gates/ harness.

Duplicate check

gh issue list and gh pr list on bendlang/bend for reuseport, SO_REUSEPORT and TCP.listen: nothing open or closed.

The IO loop is one per process; threads only run spawned `!` work, so
the only way a lightweight route uses N cores is N processes on one
port. Without SO_REUSEPORT the second process gets Fail(Address
already in use). Lemah, a Bend API framework, measured what that
costs: one Bend process with 4 threads serves a light route at 88.3k
req/s, a second process on the same port cannot start at all, and Bun
with 4 processes on one port (reusePort) serves the same route at
118.9k on the same machine.

SO_REUSEADDR was already set unconditionally on the same socket;
SO_REUSEPORT joins it under #ifdef SO_REUSEPORT (the option is not
defined on every platform clang targets, even though every platform
Bend ships for has it). The JS lane sets the numeric equivalent through
the same io_sys() FFI tcp_listen.js already uses for SO_REUSEADDR
(2/0xf on Linux, 4/0x200 on mac); it talks to libc directly and never
goes through Node's or Bun's listen options.

Considered an opt-in argument on TCP.listen instead of default-on.
Rejected: TCP.listen takes only a port, so opt-in means a new
signature; SO_REUSEADDR is already default-on in the same function;
and no existing test asserts that a second TCP.listen on a bound port
fails (grepped every test that calls TCP.listen), so nothing regresses.
The one observable trade-off: two listeners on one port by mistake now
share its connections (the kernel hashes them across listeners) instead
of the second failing. Bun (`reusePort: true`) and Node 23.1+
(`net.listen({reusePort})`) expose the same option opt-in.

tests/io/tcp_listen_shared.bend listens twice on the same port in one
process; both must answer Done{} (the second answered Fail before this
change -- checked by reverting the two effs files and rerunning).
Checked, interpreted, JS-built and C-built locally (this repo's own
bend2/main.ts, not the installed toolchain, so the edited effs are the
ones exercised): all four lanes print "first" / "second"; tcp_connect_
black_hole, tcp_listen_close, tcp_loopback, tcp_poll, tcp_send_slow_
peer, tcp_short_recv, tcp_spawn and port_bound keep their existing
output in all four lanes.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@zxv

zxv commented Sep 22, 2026

Copy link
Copy Markdown

rescuing this PR by commenting (github bug caused it to be hidden).

Comment thread bend2/effs/tcp_listen.c Outdated
Comment on lines +11 to +13
#ifdef SO_REUSEPORT
setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one));
#endif

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

On macOS, SO_REUSEPORT permits duplicate listeners, but it doesn't appear to distribute incoming connections between them. In my testing with two processes (in both C and JS), all 200 connections were handled by a single process. The new test passes, but it doesn't exercise actual traffic acceptance, so it may not catch this behavior. It might be worth documenting this limitation and adding a test for connection distribution before we present this as enabling a process-per-core server on macOS.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You are right, and the promise in the guide was too broad. Fixed in afa92fd.

On Linux the kernel does spread the load: two processes sharing one port took 100 and 100 of 200 sequential connections here (Linux 6.x, x86-64), so process-per-core holds there. I have no macOS to test on, and your result matches what the option means on that side -- BSD's SO_REUSEPORT permits the duplicate bind, and the balancing one is FreeBSD's separate SO_REUSEPORT_LB, which macOS does not have. So the guide and the comment at the call now say both: N processes share the port, Linux spreads accepted connections over them, macOS permits the bind but does not distribute.

On the test: I kept it to the duplicate bind, which is what the change guarantees on every platform, rather than adding a distribution test. Which listener accepts a given connection is the kernel's decision and differs by platform, so a cross-platform assertion would either be flaky on Linux or fail outright on macOS. If you would rather have it pinned per platform, I am happy to add it -- say the shape you want and I will write it.

Comment thread bend2/effs/tcp_listen.js Outdated
const one = new Int32Array([1]);
const level = sys.mac ? 0xffff : 1;
sys.setsockopt(fd, level, sys.mac ? 4 : 2, sys.ptr(one), 4);
sys.setsockopt(fd, level, sys.mac ? 0x200 : 15, sys.ptr(one), 4);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Both backends ignore the return value of the new setsockopt call. Injecting an option failure in JS makes the first listener report success, then the second fails with Address already in use; the original setup error disappears. Check the return value and close the socket before reporting the error, or explicitly document and test a fallback if sharing is optional

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch, and it found a second bug. Fixed in afa92fd: the call now fails like the bind, listen and fcntl beside it, closing the socket first, so an option failure is reported where it happens instead of surfacing later as the second listener's EADDRINUSE.

Writing the check is what exposed the other one: my first version put it after the bind, and the C lane's test immediately printed 'Address already in use' instead of 'second' -- the option has to be set before the bind or the kernel has already refused the duplicate. The JS lane happened to be correct because || evaluates left to right. Both lanes now set it before the bind and check the return.

I left SO_REUSEADDR's return unchecked, since changing it is outside this PR, but the same argument applies to it if you want that in a follow-up.

… spreads the load

Two things review found. The setsockopt return was ignored, so an option
failure surfaced later as the second listener's EADDRINUSE with the real
cause gone; it now fails the call like the bind, listen and fcntl beside
it, closing the socket first. Writing that check also caught a bug in the
first version of it: the call has to run before the bind, or the kernel
has already refused the duplicate -- the C lane's test printed "Address
already in use" until it moved up.

And the promise was too broad. On Linux the kernel spreads accepted
connections over the listeners: two processes sharing one port took 100
and 100 of 200 sequential connections here. On macOS the option permits
the duplicate bind but does not distribute, so N processes share the port
without sharing the load. The guide now says both, and so does the
comment at the call.

The test stays as it is: two listeners on one port is what the change
guarantees everywhere, while which listener accepts a given connection is
the kernel's to decide and differs by platform, so it is documented
rather than pinned.

Co-Authored-By: Claude Opus 5 <[email protected]>
@nicolas-abril nicolas-abril self-assigned this Sep 23, 2026
@nicolas-abril

Copy link
Copy Markdown
Collaborator

Checked this locally on macOS (arm64) against the merge base.

Concurrent runs of the TCP tests now collide. tcp_loopback, tcp_poll, tcp_short_recv, tcp_spawn and tcp_send_slow_peer find a port with tcp_listen_any, which moves to port + 1 when TCP.listen fails. With SO_REUSEPORT always on, a port held by another Bend process no longer fails, so concurrent copies share it. Running 4 copies of each test at once: base 20/20 pass; with this PR, tcp_loopback, tcp_short_recv and tcp_spawn fail 4/4 and tcp_poll 3/4. Typically one copy hangs until killed because its own client's connection was accepted by another copy. The gate runs tests one at a time, so it won't show this, but parallel local runs and any user program that probes for a free port the same way will hit it.

On macOS the first listener takes everything. With two listeners on 0.0.0.0 and the same port, the first to bind got 200/200 connections in repeated runs. So on macOS, an accidental second instance now starts without error and never receives a connection, where it used to fail with EADDRINUSE.

Given that the benefit is Linux-only, I'd take you up on the opt-in shape (e.g. a separate TCP.listen_shared(port)), which also leaves tcp_listen_any working. If it stays default-on, the tests need another way to detect a taken port, and tcp_listen_shared should probably use tcp_listen_any too, not a fixed 8730.

For what it's worth, a single listener shows no throughput change: demos/io_http_server under ab gives about 47k req/s (C) and 44k req/s (JS) on both base and this branch.

Note: this comment was written by an AI after it tested the PR for me and I reviewed the findings. If anything here is wrong, reply and I will review it myself.

…hat shares it

Review on bendlang#972 showed that SO_REUSEPORT on by default breaks the one
guarantee a probe for a free port relies on: a port another Bend process
holds no longer fails, so concurrent copies of the TCP tests share a port
and accept each other's clients. Reproduced on Linux x86-64, four copies
of each test at once, three rounds, native lane:

  test             base    default-on   this commit
  tcp_loopback     12/12    8/12        12/12
  tcp_short_recv   12/12   11/12        12/12
  tcp_spawn        12/12    8/12        12/12
  tcp_poll         12/12   10/12        12/12

On Linux the kernel spreads connections over the sharers, so an
accidental second instance silently splits traffic; on macOS, as
measured in the review, the first listener takes every connection, so
the second starts and never receives one. Both used to fail with
EADDRINUSE, and now do again.

TCP.listen sets SO_REUSEADDR only, as before bendlang#972. TCP.listen_shared
sets SO_REUSEPORT before the bind and fails when the option is refused
(ENOPROTOOPT where the platform has no SO_REUSEPORT) instead of falling
back to an owned port. Both defs share tcp_listen.c/.js; each effect sits
under its own CID guard, as in file_read.c.

tests/io/tcp_listen_shared.bend probes its port upward with
TCP.listen_shared (range 19947, clear of the other TCP tests), shares it
twice, and pins that a plain TCP.listen on it answers "Address already
in use". It passes the check, interpreted, JS and native lanes, and four
concurrent copies; with TCP.listen made shared again it prints "plain
listen shared the port" instead. The five existing TCP tests pass in the
native and JS lanes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@aldeni aldeni changed the title TCP.listen sets SO_REUSEPORT: N processes can share a port TCP.listen_shared lets N processes share a port; TCP.listen keeps owning its own Sep 23, 2026
@aldeni

aldeni commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

Thank you, you're right, and it is worse than a test-harness problem. I reproduced the collision on Linux x86-64 (native lane, four concurrent copies of each test, three rounds):

test base default-on now
tcp_loopback 12/12 8/12 12/12
tcp_short_recv 12/12 11/12 12/12
tcp_spawn 12/12 8/12 12/12
tcp_poll 12/12 10/12 12/12

On Linux the kernel spreads connections over the sharers, so an accidental second instance would silently split traffic with the first; with your macOS result, the same mistake starts and never receives a connection. Both used to fail with EADDRINUSE, which is the right default, so I took the opt-in shape (a49da27):

  • TCP.listen is back to SO_REUSEADDR only: it owns its port, so tcp_listen_any and an accidental second instance see a taken port again.
  • TCP.listen_shared(port) sets SO_REUSEPORT before the bind, and fails if the option is refused instead of quietly owning the port. Both defs share tcp_listen.c/.js, each effect under its own CID guard.
  • The guide says what each does, including that on macOS the first listener takes every connection.
  • tests/io/tcp_listen_shared.bend no longer uses a fixed port: it probes upward from 19947 with TCP.listen_shared (clear of the other TCP tests' ranges), shares the port twice, and pins that a plain TCP.listen on it answers Address already in use. Probing with the shared call is safe here because the test makes no connection: a concurrent copy that lands on the same port shares it, and the plain listen is refused either way.

The new test passes the check, interpreted, JS and native lanes, and four concurrent copies. With TCP.listen made shared again, it prints plain listen shared the port instead. The five existing TCP tests pass in the interpreted, JS and native lanes, and the table above is the same experiment rerun on this commit. This PR, #977 and #978 still apply together in any order.

I have no macOS machine, so the guide's macOS sentence rests on your measurement and @paulovitin's earlier one.

@nicolas-abril

Copy link
Copy Markdown
Collaborator

Now that it's written like this, it's clearer to me that this is more a workaround over a bend limitation than some fundamental kind of opration, so I'm inclined to close this PR in favor of maybe improving the runtime.
You can still have it as a bend package and publish it to BendHub, it will very much be appreciated. Thank you for your contribution.

If you think this is a mistake and your change should still be merged feel free to reopen and leave a comment.

@aldeni

aldeni commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for testing it on macOS and for explaining the decision. Agreed: a runtime-level answer is the better path, and closing this is fine.

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.

4 participants