Skip to content

Deployment: run realtime behind a provider-neutral same-origin WebSocket proxy #391

Open

Description

@imshashank

Goal

Make Orbit realtime work in a normal production deployment without relying on Vercel's experimental_upgradeWebSocket, while preserving the same-origin browser URL and the existing permission model.

This is the first implementation issue under #388 and closes the deployment shape tracked as DEP-002 in docs/open-source-readiness.md.

Current boundary

The code is already split more cleanly than the deployment documentation implies:

  • apps/web/src/app/api/ws/route.ts upgrades through experimental_upgradeWebSocket from @vercel/functions.
  • apps/web/src/lib/realtime/url.ts deliberately ignores NEXT_PUBLIC_REALTIME_URL in production and always resolves the browser socket to /api/ws on the page origin.
  • apps/realtime already contains a Bun WebSocket host around @orbit/realtime-server, including Redis fan-out, ticket authentication, heartbeat handling, shutdown, and a health route.
  • apps/realtime/package.json already builds a dist/index.js artifact and has a start command, but the app is documented and treated as development-only.

The missing piece is a supported production topology and its tests, not a second realtime implementation.

What to build

1. Promote apps/realtime to a production service

  • Define its complete production configuration contract.
  • Keep BETTER_AUTH_SECRET identical between web and realtime so the existing short-lived socket tickets remain verifiable.
  • Use the same Redis deployment as the web mutation publisher.
  • Connect to Postgres with the same least-privilege runtime role required by the hub.
  • Expose only the WebSocket route and minimal liveness/readiness endpoints.
  • Support graceful shutdown without abandoning authenticated connections indefinitely.

2. Keep the public socket same-origin

The browser should continue connecting to:

wss://orbit.example.com/api/ws

A reverse proxy routes that path to the realtime service while ordinary HTTP traffic goes to the standalone web service. The browser should not need the internal realtime host or port.

Provide tested examples for:

  • nginx
  • Caddy
  • Traefik

The proxy configuration must forward the upgrade headers, preserve the external host/protocol information needed by policy, and use reasonable idle timeouts for Orbit's heartbeat interval.

3. Preserve Vercel compatibility

Do not remove the existing Vercel route unless the replacement supports the production deployment currently running at orbit.noveum.ai.

Choose one explicit topology boundary:

  • retain the Vercel route and use the dedicated service only when a deployment flag is enabled, or
  • move the Vercel deployment to the same portable service before deleting the route.

Do not infer the topology from a loosely related environment variable. Configuration should fail clearly when a selected topology is incomplete.

4. Keep ticket and permission behavior unchanged

  • Tickets remain short-lived and are sent in the first socket message, never in a URL.
  • A ticket remains bound to the user and selected workspace.
  • Scope and membership checks remain server-side.
  • Revoked sessions and memberships close or refuse the connection as they do today.
  • The public realtime service must not trust a forwarded user identity from the reverse proxy.
  • The service port should be private by default in the production Compose network.

Acceptance tests

  1. Build the standalone web artifact and the realtime artifact from a clean checkout.
  2. Start web, realtime, Postgres, Redis, and object storage through a production-shaped Compose profile.
  3. Put nginx, Caddy, or Traefik in front and access only one public HTTPS origin.
  4. Sign in in two independent browser contexts, open the same workspace, change an issue in one, and observe the update in the other without refresh.
  5. Prove issue, project, doc, notification, membership, and forced-logout events still reach only entitled connections.
  6. Restart the realtime container and prove both browsers reconnect and resume receiving permitted changes.
  7. Run at least two realtime instances against the same Redis and prove fan-out reaches clients connected to different instances.
  8. Present an expired, malformed, wrong-workspace, and revoked ticket and prove each is rejected without leaking workspace data.
  9. Prove the existing Vercel deployment path still passes its WebSocket test until it is deliberately migrated.
  10. Add CI that fails if the reverse proxy cannot obtain a 101 upgrade or if the two-browser synchronization check fails.

Health contract

Separate liveness from readiness:

  • liveness says the process can answer
  • readiness stays false until the hub can use the dependencies needed to accept and service connections

Do not expose connection counts, tenant identifiers, dependency URLs, or internal topology from the public health response. SEC-014 tracks the broader health-surface rule.

Documentation

Update:

  • README.md
  • docs/architecture.md
  • docs/configuration.md
  • docs/self-hosting.md
  • docs/troubleshooting.md
  • SECURITY.md
  • CLAUDE.md
  • CONTRIBUTING.md

Remove statements that the standalone path cannot do realtime only after the production-shaped test proves otherwise.

Likely files

  • apps/realtime/src/index.ts
  • apps/realtime/src/env.ts
  • apps/realtime/src/server.ts
  • apps/web/src/app/api/ws/route.ts
  • apps/web/src/lib/realtime/url.ts
  • packages/realtime-client/
  • packages/realtime-server/
  • .github/workflows/ci.yml
  • infra/ or a new deployment directory for proxy fixtures

Not part of this issue

  • Durable outbox and replay-gap repair tracked by RT-001
  • Production image construction and the complete Compose release, which will consume this topology in a sibling issue
  • Collaborative Yjs document editing
  • A public unauthenticated realtime endpoint

Design note required before implementation

Comment with the proposed topology switch, proxy path, health contract, and Vercel migration plan before opening a large pull request. The preferred result is one realtime hub implementation with two supported hosts, not parallel behavior that drifts.

Activity

  1. self-assigned this
    on Sep 3, 2026
  2. added
    help wanted
    on Sep 3, 2026
  3. imshashank commented on Sep 4, 2026

    @imshashank
    ContributorAuthor

    Proposed implementation design

    Decision

    Keep one public realtime URL everywhere:

    wss://<orbit-origin>/api/ws
    

    Do not re-enable a production NEXT_PUBLIC_REALTIME_URL override and do not teach the browser about an internal realtime host.

    The deployment layer selects the host:

    • Vercel: the existing Next.js /api/ws route continues to call experimental_upgradeWebSocket.
    • Provider-neutral deployment: the reverse proxy intercepts /api/ws before it reaches Next.js and forwards it to apps/realtime:3100.

    This preserves the current browser code, same-origin cookies/origin policy, socket-ticket flow, and Vercel production deployment. It also avoids a runtime topology flag in the web application: the same build can sit behind either routing topology.

    Realtime service changes

    Promote apps/realtime from “development only” to a supported host for the existing @orbit/realtime-server hub.

    1. Accept upgrades only on an explicit path, defaulting to /api/ws; currently any request with an Upgrade header can reach the upgrade call.
    2. Reject unexpected browser origins against the configured public Orbit origin. Do not trust forwarded user or workspace headers. Authentication remains the signed first-message ticket.
    3. Keep BETTER_AUTH_SECRET, Postgres, and Redis shared with web. Every replica must use the same ticket verifier and Redis fan-out.
    4. Bind to 0.0.0.0 inside the private container network but publish no host port in the production Compose profile.
    5. Keep graceful shutdown and bounded forced close. Mark the instance unready before closing the hub so a proxy stops sending new upgrades during drain.

    Health contract

    Replace the public stats-shaped health response with two minimal endpoints:

    GET /livez   -> 200 {"status":"ok"} while the process can answer
    GET /readyz  -> 200 {"status":"ok"} only when Redis is ready and a bounded DB probe succeeds
                     503 {"status":"unavailable"} otherwise
    

    Connection counts, Redis state names, dependency URLs, tenant identifiers, and internal topology stay out of the response. Detailed stats remain available only to tests or an internal operator surface.

    The WebSocket upgrade path must not wait for a health probe, Redis command, or database query before upgrading. Ticket authentication continues inside the hub after the connection opens.

    Proxy fixtures

    Keep reviewed examples under a deployment directory rather than scattered documentation snippets.

    Caddy

    Caddy handles WebSocket upgrade automatically:

    orbit.example.com {
      @realtime path /api/ws
      reverse_proxy @realtime realtime:3100
      reverse_proxy web:3000
    }

    nginx

    Use HTTP/1.1, explicit Upgrade/Connection headers, the external Host, and an idle timeout longer than Orbit’s heartbeat window. Route only exact /api/ws traffic to realtime; ordinary /api/* remains on web.

    Traefik

    Use two routers on the same entrypoint/domain. The /api/ws Path rule has higher priority and targets the realtime service; the fallback router targets web. No public realtime port is exposed.

    All three fixtures must pass the same smoke suite rather than being documentation-only examples.

    CI topology

    Add a production-shaped lane separate from the existing development E2E lane:

    1. Build the copied standalone web artifact and the Bun realtime artifact.
    2. Start Postgres, Redis, object storage, web, and two realtime replicas.
    3. Put one proxy fixture in front and access only the proxy origin.
    4. Obtain a socket ticket through the web application.
    5. Open clients routed to different realtime replicas and prove Redis fan-out.
    6. Change an issue/project/doc and prove the second browser updates without refresh.
    7. Restart one realtime replica and prove reconnect succeeds.
    8. Exercise expired, malformed, revoked-session, wrong-workspace, and removed-membership tickets.
    9. Assert /api/ws returns a 101, /livez is minimal, /readyz fails when Redis or DB is unavailable, and no dependency port is public.

    Run nginx on every relevant PR because it requires the most explicit WebSocket configuration. Run Caddy and Traefik in the nightly/release matrix, or all three on a deployment-specific PR when runtime permits.

    Vercel migration boundary

    The first PR does not delete or rewrite apps/web/src/app/api/ws/route.ts. Vercel’s existing path remains covered by its unit/E2E tests.

    After the portable stack has production evidence, a separate decision may move the hosted Orbit deployment behind the dedicated realtime service. Only then should removal of experimental_upgradeWebSocket be considered. Until that migration is deliberate, both hosts wrap the same @orbit/realtime-server implementation.

    Configuration

    Proposed production variables for the dedicated service:

    REALTIME_PORT=3100
    REALTIME_PATH=/api/ws
    NEXT_PUBLIC_APP_URL=https://orbit.example.com
    BETTER_AUTH_SECRET=<same value as web>
    DATABASE_URL=<same installation database>
    REDIS_URL=<same installation Redis>
    

    Use the existing public-app URL as the allowed browser origin rather than adding a second redundant origin variable unless multiple public origins become a real requirement. Production preflight must reject localhost/non-HTTPS public origins outside an explicitly marked local test profile.

    Pull-request split

    1. Restrict path/origin, add minimal live/readiness, and test the dedicated server in isolation.
    2. Add one same-origin proxy fixture and the production-shaped two-client/two-replica test.
    3. Add the other proxy fixtures and documentation updates.
    4. Let Deployment: publish production images and a complete Compose stack #392 consume the proven topology in versioned images and the full production Compose stack.

    No PR in this sequence should alter the hosted Vercel route or be merged automatically.

  4. imshashank commented on Sep 4, 2026

    @imshashank
    ContributorAuthor

    First implementation slice

    #397 implements the smallest reviewable portion of the design:

    • exact same-origin /api/ws upgrade boundary for the dedicated Bun host
    • optional normalized browser-origin allowlist
    • minimal /livez and /readyz responses, with /health retained as a minimal readiness alias
    • optional readiness callback for the later bounded database probe
    • focused path/origin tests

    The existing Vercel WebSocket route is unchanged, and origin enforcement is not silently enabled without validated production configuration.

    Fresh-clone verification passed:

    bun install --frozen-lockfile
    bun test apps/realtime/tests/deployment-boundary.test.ts
    bunx biome check apps/realtime/src/server.ts apps/realtime/tests/deployment-boundary.test.ts
    bun run --filter '@orbit/realtime' typecheck
    docker compose up -d
    bun run --filter '@orbit/realtime' test
    

    The PR is open for normal review and has not been merged. The proxy fixtures and production-shaped two-browser/two-replica test remain follow-up work.

  5. imshashank commented on Sep 6, 2026

    @imshashank
    ContributorAuthor

    First slice merged in #397: exact /api/ws upgrade boundary, optional origin allowlist, /livez and /readyz, and the dev socket and tests moved onto the path. Still open here: the proxy fixtures (nginx first), the production-shaped two-browser, two-replica test, and the documentation updates. #392 consumes this once those exist.

  6. added
    area: realtime
    roadmap
    p1 high
    size: large
    points: 8
    on Sep 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area: realtimehelp wantedp1 highpoints: 8roadmapsize: large

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions