Relatry Architecture: Scaling a $0 Referral Graph on Serverless Postgres architecture illustration
2026-11-21 10 min journal / relatry-architecture-scaling-referral-graph-serverless-postgres

Relatry Architecture: Scaling a $0 Referral Graph on Serverless Postgres

Length
2210 words
Read
10 min

Key takeaways

  • Invert the join before you traverse: Filtering 2nd-degree candidates by target hiring companies first turns an O(N² × M)-shaped nested loop into an indexed join over a much smaller set in Postgres.

  • Browser-side gatekeeping protects free LLM quotas: Running pdfjs-dist in the client keeps PDF parsing off the serverless heap and blocks unreadable image resumes before they consume API rate limits.

  • Status rows can replace Redis for short jobs: Next.js after() paired with Neon rows (queued → processing → ready) is enough for multi-provider AI failover when work finishes inside one function window.

  • Tenant isolation requires strict per-user boundaries: Public company metadata and logos can be cached at the edge, while connection graphs must stay isolated per user_id with soft-delete reconciliation on full CSV syncs.

  • $0 production means matching workloads to quota shapes: Stateless HTTP drivers (@neondatabase/serverless) and a four-provider no-card LLM chain avoid TCP connection exhaustion and single-vendor daily caps — within free-tier terms, not as a permanent commercial SLA.


Building a 2nd-degree referral engine on a $0 infrastructure budget

Job seekers rarely lack technical skills; they lack warm introductions into companies actively hiring. When I started building Relatry, the goal was straightforward: map a user's 1st- and 2nd-degree professional connections against live job openings so they can find an insider willing to refer them—while running the entire production stack on free tiers with zero attached credit cards.

Building a graph-heavy application on serverless free tiers immediately exposes three bottlenecks: connection exhaustion on managed Postgres, rate-limit walls on free LLM APIs during resume parsing, and cubic query complexity when traversing 2nd-degree networks.


Why naive serverless graph and parsing designs fail

  • Serverless TCP connection exhaustion: Traditional database drivers open persistent TCP sockets per serverless container. On a free database with a small direct-connection cap, a sudden spike of concurrent Next.js API invocations triggers too many connections crashes.

  • Cubic traversal in 2nd-degree referral queries: Walking every 1st-degree connection (N), expanding every 2nd-degree connection (N), and matching against open jobs (M) creates an O(N² × M) nested loop that times out inside serverless execution windows.

  • Server-side PDF parsing bloat: Running heavy PDF binaries inside serverless functions risks hitting bundle size limits and wastes free LLM daily request quotas when users upload scanned images or corrupted files.

  • Single-provider AI rate limits: Relying on one free-tier LLM endpoint fails under burst uploads because free quotas enforce strict Requests Per Minute (RPM) and Tokens Per Minute (TPM) ceilings.


How Relatry works: a 60-second overview

Relatry pairs a Next.js App Router frontend on Vercel with Neon Serverless Postgres (and Neon Managed Better Auth) plus a four-provider no-card LLM failover chain. Users ingest their network by uploading a LinkedIn Connections.csv (or equivalent export), upload a PDF resume validated in the browser, and query indexed Postgres tables to uncover 1st- and 2nd-degree referral paths.

Architecture diagram

System topology: client gatekeepers, edge cache, and Neon storage

Relatry separates public lookup data from private connection graphs across four layers:

  1. Ingestion layer: A client-side CSV parser (PapaParse) reads the user's Connections.csv export and upserts people and edges into Postgres. There is no live social-network API in this path — the user's file is the source of truth for the graph.

  2. Client gatekeeper layer: pdfjs-dist extracts text and validates character density directly in the browser before any resume payload reaches the backend.

  3. Compute and background queue layer: Next.js App Router endpoints handle authentication via Neon Managed Better Auth (neon_auth.user) and offload slow AI extraction and referral matching into after() background callbacks.

  4. Storage and edge cache layer: Neon Postgres stores the relational schema (users, people, user_connections, connection_sync_runs, user_resumes, user_job_feeds, user_notifications, plus shared caches). Public company logo and profile routes set long-lived Cache-Control so repeat hits can be served from Vercel's CDN edge; private graph routes still hit Neon.


Request path: non-blocking resume upload and AI failover

When a user drops a resume PDF, the frontend validates it locally, enqueues a database record quickly, and processes extraction asynchronously so the user can continue exploring their network graph immediately.

Architecture diagram
  1. Client validation: pdfjs-dist checks page count, text length, and alphanumeric ratio. Scanned images or font-corrupted PDFs fail immediately on the client with actionable formatting feedback.

  2. Fast enqueue: POST /api/resumes/upload verifies the session via auth.getSession(), inserts a queued row into user_resumes, schedules after(), and returns HTTP 202 Accepted.

  3. Sequential AI failover: Inside after(), the worker attempts structured JSON extraction through Google AI Studio (gemini-2.5-flash), failing over on HTTP 429 or 503 errors to Groq (llama-3.3-70b-versatile), Mistral AI (mistral-small-latest), and finally OpenRouter :free models.

  4. Notification dispatch: Once user_resumes updates to ready, the worker writes a deduplicated alert into user_notifications (dedupe_key) so the UI updates on its next lightweight poll.


Data path: inverting the 2nd-degree referral query

In Relatry's schema, user_connections maps a user_id to a canonical person_id in people, while users.person_id links registered Relatry users back to their canonical people entry. To prevent stale edges when someone disappears from a later CSV upload, every full sync tracks a connection_sync_runs ID and soft-deletes missing rows via removed_at.

To find a 2nd-degree path (You → Mutual Friend → Target Employee at Hiring Company) without scanning every connection's network, Postgres inverts the join order:

Architecture diagram
  1. Extract target companies: A CTE pulls distinct normalized company names from the user's matched user_job_feeds.

  2. Filter 2nd-degree candidates first: Using a composite partial index on (lower(company), user_id) WHERE removed_at IS NULL, Postgres narrows user_connections strictly to people working at those target hiring companies.

  3. Intersect with 1st-degree bridges: The query joins those filtered rows against users (u2.person_id = uc1.person_id) to identify which of the current user's 1st-degree connections (u2.id <> $1) hold that second-degree link, while excluding anyone already in the user's own 1st-degree list.


Failure domains and blast radius

Component / Failure Blast Radius Mitigation & Recovery
Primary LLM rate limit (429) Single background resume parse job after() worker catches the error and falls through Gemini → Groq → Mistral → OpenRouter within the function duration cap.
All free LLM providers exhausted Resume remains unparsed; graph browsing unaffected Row in user_resumes transitions to status = failed with error_message; user can retry without losing connection data.
Incomplete Connections.csv sync Stale connection list if the upload is abandoned mid-import connection_sync_runs tracks complete = false; soft-deletes (removed_at) only execute when a full CSV sync finishes cleanly.
Neon compute idle cold start First private request after idle can feel slower; rare timeouts if the client gives up early Keep auth session data cached for a short TTL, serve public company routes from CDN cache, and surface retry-friendly errors on the first wake.
Unreadable / scanned PDF upload Single upload attempt Blocked in browser by pdfjs-dist before reaching Vercel, consuming zero server compute or LLM tokens.

Connections.csv ingest path

Every personal edge enters Relatry the same way: the user exports LinkedIn Connections.csv (or an equivalent CSV) and uploads it in the browser. PapaParse reads the file locally, normalizes company/title fields, and posts batches to an authenticated upsert API. There is no live social graph pull in this architecture.

Architecture diagram
  1. Parse on the client: Keep large CSV parsing off the serverless CPU budget.

  2. Upsert under user_id: UNIQUE (user_id, person_id) prevents cross-tenant corruption.

  3. Reconcile with removed_at: Only a completed sync soft-deletes edges that did not reappear in the new CSV.


Deep dive: client-side PDF gatekeeping and JSON schema enforcement

Running PDF text extraction in the browser solves two problems at once: it keeps server memory footprints small and protects daily LLM token budgets from junk inputs.

typescript
// Browser gatekeeper checks before hitting /api/resumes/upload
const alphanumericRatio =
  (cleaned.match(/[a-zA-Z0-9]/g)?.length || 0) / cleaned.length;

if (cleaned.length < 120 || alphanumericRatio < 0.55) {
  return {
    ok: false,
    tip: "Export a standard text-based PDF rather than a flattened image or custom-font graphic.",
  };
}

Once clean text reaches the server, each provider in the failover chain is constrained to return deterministic JSON keys (currentTitle, experienceYears, skills, targetRoles, preferredLocations, pastCompanies) using Gemini's responseSchema or OpenAI-compatible response_format: { type: 'json_object' }. Truncating input text to a bounded character window keeps payloads inside stricter Tokens Per Minute limits while retaining work history and skills.


Current progress and tradeoffs

Data-store tradeoffs in Relatry are intentional: transactional referral paths and CSV upserts stay on Neon Postgres B-trees, while a Redis/BullMQ queue or columnar warehouse would add free-tier cost and operational surface without helping 2-hop point lookups.

Relatry's authentication (Neon Managed Better Auth), Postgres schema, Connections.csv ingest path, client-side PDF gatekeeper, and non-blocking 4-tier resume parser are running on Vercel Hobby with Neon. The "$0" claim means no credit cards attached to these free tiers today — not that quotas, region cold starts, or commercial ToS never become a constraint.

Architectural Decision Benefit Cost
Client-side pdfjs-dist extraction No server PDF binary; blocks bad files before LLM calls Depends on client browser CPU; cannot OCR legitimate image-only scans
Next.js after() + Postgres status rows Non-blocking UX without Redis/BullMQ Bound by serverless max duration; no durable exponential retry queue
Stateless @neondatabase/serverless HTTP driver Avoids TCP connection exhaustion across concurrent Vercel functions Slightly higher per-query overhead than a local pool
Inverted SQL join over a dedicated graph DB 2nd-degree paths stay inside free Postgres Fine for 2 hops; 3rd/4th-degree crawls would need an analytical engine
Four-provider no-card LLM chain Survives individual free-tier RPM/RPD caps Adapter logic across different JSON-schema APIs
Connections.csv as the graph source User-owned data, no partner API keys, fits $0 quotas Freshness depends on the user re-exporting and re-uploading the CSV

What I would steal for a smaller stack

  • Move input validation to the client edge: If your backend calls metered or rate-limited AI APIs, run lightweight parsing and sanity checks in the browser first so malformed files never consume backend quota.

  • Use after() plus a status column before adopting a message broker: For async jobs that finish in under tens of seconds (document extraction or notification fan-out), a Postgres status column and Next.js after() give you non-blocking responses without managing a separate queue service.

  • Invert graph queries around the selective filter: When querying 2-hop relationships in SQL, always filter by the smallest selective set first (such as target companies) rather than expanding every user's friend list outward.

  • Prefer user-exported CSV over partner APIs for MVP graphs: A Connections.csv upload keeps the product legal and free while you prove the referral UX — defer paid directory APIs until the product needs live freshness.


FAQ

How does Relatry prevent one user's CSV import from corrupting another user's graph?

Every personal edge lives in user_connections scoped by user_id with a UNIQUE (user_id, person_id) constraint. Public metadata like company_logos and company_profiles is shared globally, while all graph queries filter strictly by the authenticated user's user_id.

What happens when someone is missing from a later Connections.csv upload?

Each complete sync creates a connection_sync_runs record and stamps last_seen_run_id on every active contact returned from that CSV. Once a full sync completes (complete = true), any row belonging to that user from an earlier run is stamped with removed_at and excluded by partial indexes (WHERE removed_at IS NULL).

Why keep live referral queries on Neon instead of an analytical warehouse like MotherDuck?

Single-user referral lookups and CSV upserts are transactional point queries that execute in milliseconds using B-tree indexes in Postgres. Columnar warehouses like MotherDuck are better reserved for offline batch analytics or multi-gigabyte public company registries that would exceed Neon's free storage tier.

Where does Relatry get connection data from?

Users upload LinkedIn Connections.csv (or an equivalent export). Relatry parses that file in the browser and upserts edges into user_connections. This architecture does not call a live LinkedIn graph API.

Can this architecture run commercially on Vercel's free Hobby plan?

Technically, the components fit within Hobby bandwidth and serverless execution limits if polling intervals stay throttled. Hobby terms restrict usage to non-commercial projects — monetizing would require upgrading to Vercel Pro or moving the frontend elsewhere.


Sources

Questions

How does Relatry prevent one user's CSV import from corrupting another user's graph?

Every personal edge lives in user_connections scoped by user_id with a UNIQUE (user_id, person_id) constraint. Shared company metadata can be cached globally, while graph queries always filter by the authenticated user_id.

What happens when someone is missing from a later Connections.csv upload?

Each complete sync creates a connection_sync_runs record and stamps last_seen_run_id on returned contacts. When a full sync finishes cleanly, rows from earlier runs that did not reappear are stamped with removed_at and excluded by partial indexes.

Why keep live referral queries on Neon instead of an analytical warehouse?

Single-user referral lookups and CSV upserts are transactional point queries that run in milliseconds on B-tree indexes in Postgres. Columnar warehouses fit offline analytics better than interactive 2-hop path lookups.

Where does Relatry get connection data from?

Users upload LinkedIn Connections.csv (or an equivalent export). Relatry parses that file client-side and upserts edges into user_connections — there is no live LinkedIn graph API in this architecture.

Can this stack run on free Vercel Hobby plus Neon?

The technical pieces fit free-tier shapes if polling stays light, but Vercel Hobby is for non-commercial use. Monetizing needs Pro or another host.

Related reading