PostGraphile
Audited from github.com/graphile/postgraphile
PostGraphile compiles PostgreSQL schemas, tables, and functions into high-performance, extensible GraphQL APIs using the Grafast execution engine.
- Language
- TypeScript
- Database
- PostgreSQL
- License
- MIT
- Running for
- 6 years
- Team
- 2-5 People
Why this architecture
Synthesizing GraphQL APIs directly from PostgreSQL catalogs eliminates manual resolver boilerplate while Grafast planning solves N+1 query overhead at the database layer.
Tech stack by layer
6 technologies · audited Sep 17, 2026- TypeScriptStrictly typed development environment across all monorepo packages and CLI tools.
- Node.jsTarget server runtime requiring Node 22 or newer across workspace engines.
- GraphQLGraphQL schema generation and execution engine powered by Grafast.
- PostgreSQLIntrospects schemas, views, stored procedures, and Row-Level Security policies.
- DocusaurusStatic documentation framework powering the postgraphile, grafast, and graphile-build portals.
PostGraphile architecture diagram
Open SVGDiagram as text
- GraphQL clients (queries) → Grafserv (HTTP adapters): GraphQL over HTTP
- Ruru (GraphiQL IDE) → Grafserv (HTTP adapters): explore
- Grafserv (HTTP adapters) → Grafast (plan-based execution): execute
- Grafast (plan-based execution) → dataplan-pg (SQL query plans): steps
- dataplan-pg (SQL query plans) → PostgreSQL (tables · functions · RLS): SQL
- graphile-build-pg (schema from catalog) → PostgreSQL (tables · functions · RLS): introspect
- graphile-build-pg (schema from catalog) → Grafast (plan-based execution): schema
Key architectural decisions
5 decisions- 01
Grafast operation planning replaces traditional GraphQL resolvers
PostGraphile v5 moves away from naive resolver delegation by adopting Grafast (grafast/grafast). Grafast analyzes the GraphQL query document as an execution plan tree, merging related operations and eradicating the N+1 problem.
- 02
PostgreSQL database reflection via pg-introspection and dataplan-pg
Rather than manual schema declaration, PostGraphile queries the PostgreSQL system catalogs through @dataplan/pg, automatically synthesizing GraphQL types, arguments, filters, and mutations directly from table definitions.
- 03
Crystal monorepo unifies core execution, plugins, and tooling
The repository (known as Graphile Crystal) houses Grafast, PostGraphile v5, Graphile Build, Ruru GraphiQL explorer, and utility crates in a single Yarn workspace, ensuring synchronized releases and cross-package type guarantees.
- 04
Framework-agnostic HTTP adapters via Grafserv
Grafserv (grafast/grafserv) abstracts the HTTP transport layer, providing native plug-and-play middleware for Node.js http, Express v4, Fastify v4/v5, Koa v2, Hono v4, and AWS Lambda without rewriting core query handlers.
- 05
Row-Level Security (RLS) enforcement inside PostgreSQL transactions
Authentication context (JWT claims, user roles) is passed into PostgreSQL session variables via SET LOCAL, delegating data access control and tenant isolation directly to PostgreSQL Row-Level Security policies.
How PostGraphile is built
How PostGraphile is structured
PostGraphile (residing in the Graphile Crystal monorepo) is organized as a modular TypeScript workspace governed by Yarn Modern (yarn.lock, .yarnrc.yml). The repository splits functionality across several key namespaces:
grafast/: The next-generation GraphQL planning and execution engine. It includesgrafast/grafast(the core planning engine),grafast/dataplan-pg(PostgreSQL step classes that translate field selections into SQL query plans),grafast/grafserv(the HTTP server transport layer), andgrafast/ruru(the GraphiQL exploration IDE).graphile-build/: The plugin-driven schema synthesis layer (graphile-build,graphile-build-pg), responsible for reading database catalogs and constructing the GraphQL schema AST through hook pipelines.postgraphile/: The top-level CLI (postgraphile/pgl), preset libraries (Amber, Relay, v4 compatibility), and documentation website (postgraphile/website).utils/: Low-level database introspection (utils/pg-introspection), SQL generation AST helpers (utils/pg-sql2), and configuration loaders (utils/graphile-config).
Frontend
PostGraphile does not ship a traditional end-user application frontend; instead, it delivers developer-facing exploration tooling centered around Ruru (grafast/ruru, grafast/ruru-components).
Ruru is a customized, Grafast-flavored distribution of GraphiQL built with React 19 (react, react-dom in grafast/ruru-components/package.json). It incorporates the GraphiQL plugin ecosystem (@graphiql/plugin-explorer, @graphiql/plugin-history, @graphiql/plugin-doc-explorer) and Mermaid diagram rendering (mermaid version 11) for visualizing Grafast query execution plans. The Ruru interface is bundled via Webpack (webpack.config.mts) and served either as an interactive web route or as a standalone CLI documentation server.
Backend & APIs
The backend engine is written entirely in strict TypeScript targeting modern Node.js environments ("node": ">=22" declared across package engines).
At the center of PostGraphile v5 is Grafast. Traditional GraphQL servers execute queries by invoking resolver functions recursively on each node in the GraphQL AST, which frequently leads to the infamous N+1 query problem. Grafast inverts this model: during the planning phase, it constructs a dependency graph of "steps" (using @dataplan/pg for database operations). When a query requests nested relations (such as users, their posts, and comments), Grafast plans a single, consolidated SQL query using lateral joins or subqueries, fetching all required data in one round trip.
HTTP serving is decoupled through Grafserv (grafast/grafserv). Grafserv implements standard transport protocols (including GraphQL-over-HTTP, incremental delivery, and SSE) while offering zero-cost adapters for popular Node.js frameworks:
- Node.js native
http.createServer - Express v4 (
grafserv/express/v4) - Fastify v4 and v5 (
grafserv/fastify/v4,grafserv/fastify/v5) - Koa v2 (
grafserv/koa/v2) - Hono (
grafserv/hono/v4) - AWS Lambda (
grafserv/lambda/v1)
Data & persistence
PostGraphile does not manage a proprietary storage engine; rather, it treats PostgreSQL as the primary application engine:
- Introspection: Using
utils/pg-introspection, PostGraphile connects to PostgreSQL, queryingpg_catalogtables to discover tables, views, composite types, constraints, foreign keys, and stored functions. - Smart Comments: Developers annotate PostgreSQL objects with SQL comments (e.g.,
COMMENT ON COLUMN users.password_hash IS '@omit';) to control GraphQL field visibility, naming inflections, and mutation behaviors without writing TypeScript code. - SQL Execution: The engine constructs parameterized SQL queries using
@dataplan/pgandutils/pg-sql2, executing queries against standard PostgreSQL connection pools (pg). - Security via RLS: Authentication credentials (such as user IDs or tenant scopes extracted from JWTs) are injected into the PostgreSQL transaction context using
SET LOCAL jwt.claims.user_id = .... The PostgreSQL engine then applies Row-Level Security (RLS) policies to enforce access control directly within the database engine.
Build, test & deploy
The development lifecycle in the monorepo is managed via Yarn workspaces and automated pipelines:
- Compilation: Project packages compile using project references in TypeScript (
tsc -b). - Testing: The repository uses Jest (
jest.config.js) alongside custom serializers (utils/jest-serializer-graphql-schema) that verify emitted GraphQL schemas and SQL plan ASTs against regression snapshots. - Continuous Integration: GitHub Actions workflows in
.github/workflowsexecute linting (lint.yml), cross-version PostgreSQL matrix tests (test.yml), and documentation linting with Vale (vale.yml). - Release Automation: Changesets (
.changeset/config.json) automate semantic versioning, generating changelogs and publishing scoped packages to npm.
Self-hosting notes
Deploying PostGraphile requires minimal infrastructure:
- A PostgreSQL instance (version 12 or newer, with version 16+ recommended for enhanced query planning).
- A Node.js container or serverless function running the
@graphile/postgraphileCLI or embedded in an existing Express/Fastify service. - Database credentials with appropriate permissions to read target schemas and execute functions.
PostGraphile can run as a standalone container using the pgl CLI (postgraphile/pgl), connecting to PostgreSQL via a standard connection string and exposing the GraphQL endpoint on a configurable HTTP port.
What to copy (and what not to)
Architectural insights from PostGraphile:
- Plan-based execution over resolvers: Replacing naive resolver execution trees with unified planning passes (the Grafast pattern) eliminates N+1 query bottlenecks at the architectural root rather than applying ad-hoc batching with DataLoader.
- Leveraging the database as the security boundary: Delegating authorization rules to PostgreSQL Row-Level Security policies guarantees that permissions are enforced consistently, whether queries originate from GraphQL, admin scripts, or background workers.
- Transport decoupling: Separating protocol parsing and execution from HTTP frameworks (as Grafserv does) makes libraries adaptable across Express, Fastify, Hono, and serverless environments.
Avoid attempting database schema introspection if your database schema lacks clean foreign key relationships or contains thousands of unpartitioned tables, as generating complete GraphQL schemas from unstructured relational schemas can produce bloated, unintuitive APIs.
Sources & repo audit
- package.json (Yarn workspace scripts, topological builds, Node 22+ engine)
- grafast/grafast/package.json (Grafast cutting-edge GraphQL planning and execution engine)
- grafast/dataplan-pg/package.json (PostgreSQL step classes and query optimization plans)
- postgraphile/pgl/package.json (PGL CLI and PostGraphile preset configurations)
- grafast/ruru/package.json (Grafast-flavoured GraphiQL distribution)
Independent analysis of repository at github.com/graphile/postgraphile. Spotted an inaccuracy? Use the claim form to request a correction.
Show this stack on your README or website
[](https://stackitfast.com/project/postgraphile)Paste it into your README. It shows your current stack and links to this page.
Scaffold it with your agent
Paste this prompt into Claude Code, Cursor, Windsurf or AGY to start a project with PostGraphile's architecture.
- 1Copy the promptThe full markdown spec, with every layer and decision.
- 2Open your AI toolClaude Code, Cursor, Windsurf or Copilot, in a new repo.
- 3Paste and scaffoldUse it as the first instruction; review before you ship.
# MISSION: Scaffold "PostGraphile" Production Architecture
You are an expert Senior Staff Software Architect and Full-Stack Engineer. Your mission is to scaffold and implement a production-grade, highly reliable, and modular codebase following the proven architecture of **PostGraphile**.
---
## 1. PROJECT SPECIFICATIONS & BENCHMARK
- **Reference Architecture**: PostGraphile
- **What It Does**: PostGraphile compiles PostgreSQL schemas, tables, and functions into high-performance, extensible GraphQL APIs using the Grafast execution engine.
- **Domain & Category**: Automated GraphQL API Engine
- **Production Scale**: 2-5 People
- **Development Mode**: CLASSIC
- **Architectural Rationale**: Synthesizing GraphQL APIs directly from PostgreSQL catalogs eliminates manual resolver boilerplate while Grafast planning solves N+1 query overhead at the database layer.
- **Live Website Reference**: https://graphile.org/postgraphile
- **Source Repository**: https://github.com/graphile/postgraphile
---
## 2. PRODUCTION TECH STACK
- **Full Stack Array**: TypeScript, Node.js, GraphQL, PostgreSQL, Yarn, React
- **Primary Language(s)**: TypeScript, PLpgSQL, JavaScript
- **License of the reference repo**: MIT
- **Frontend**: React — Renders the Ruru GraphiQL explorer components in grafast/ruru-components.; GraphiQL — Interactive in-browser GraphQL query execution IDE distributed through the ruru package.
- **Backend & APIs**: TypeScript — Strictly typed development environment across all monorepo packages and CLI tools.; Node.js — Target server runtime requiring Node 22 or newer across workspace engines.; GraphQL — GraphQL schema generation and execution engine powered by Grafast.
- **Data & persistence**: PostgreSQL — Introspects schemas, views, stored procedures, and Row-Level Security policies.
- **Infrastructure & deploy**: Yarn — Yarn modern workspace manager orchestrating topological package builds and testing.; Jest — Monorepo unit and integration test runner utilizing custom GraphQL schema serializers.
- **Tooling, testing & ops**: Docusaurus — Static documentation framework powering the postgraphile, grafast, and graphile-build portals.
---
## 3. KEY ARCHITECTURAL DECISIONS (audited from https://github.com/graphile/postgraphile @ 566caa3)
1. **Grafast operation planning replaces traditional GraphQL resolvers**: PostGraphile v5 moves away from naive resolver delegation by adopting Grafast (grafast/grafast). Grafast analyzes the GraphQL query document as an execution plan tree, merging related operations and eradicating the N+1 problem.
2. **PostgreSQL database reflection via pg-introspection and dataplan-pg**: Rather than manual schema declaration, PostGraphile queries the PostgreSQL system catalogs through @dataplan/pg, automatically synthesizing GraphQL types, arguments, filters, and mutations directly from table definitions.
3. **Crystal monorepo unifies core execution, plugins, and tooling**: The repository (known as Graphile Crystal) houses Grafast, PostGraphile v5, Graphile Build, Ruru GraphiQL explorer, and utility crates in a single Yarn workspace, ensuring synchronized releases and cross-package type guarantees.
4. **Framework-agnostic HTTP adapters via Grafserv**: Grafserv (grafast/grafserv) abstracts the HTTP transport layer, providing native plug-and-play middleware for Node.js http, Express v4, Fastify v4/v5, Koa v2, Hono v4, and AWS Lambda without rewriting core query handlers.
5. **Row-Level Security (RLS) enforcement inside PostgreSQL transactions**: Authentication context (JWT claims, user roles) is passed into PostgreSQL session variables via SET LOCAL, delegating data access control and tenant isolation directly to PostgreSQL Row-Level Security policies.
---
## 4. NON-NEGOTIABLE ARCHITECTURAL GUARDRAILS
1. **Monorepo & Modular Separation**:
- Structure as a Turborepo monorepo with strict package boundaries:
- `apps/web`: Application UI, routing, layouts, and server endpoints.
- `packages/ui`: Shared design tokens, CSS variables, and Radix UI primitive components.
- `packages/db`: Database schemas, client singleton, declarative migrations, and seed scripts.
- `packages/config`: Shared TypeScript, ESLint, and build configurations.
2. **Strict Type Safety & Zero `any` Policy**:
- Enable `strict: true`, `noImplicitAny: true`, and `strictNullChecks: true`.
- Validate ALL external inputs, API request bodies, and query parameters with **Zod** schemas before execution.
3. **Frontend & Rendering Guidelines**:
- Isolate interactive UI state to leaf components. Keep core pages lightweight and performant.
4. **Design System & Aesthetics**:
- Keep every color, radius, shadow and font in a single token file (CSS variables) and consume tokens everywhere; never hardcode hex values in components.
- Prefer crisp 1px borders and one subtle shadow scale over blurry default shadows. Pair one sans-serif for body/headings with one monospace for tags, badges, metrics, and code.
5. **Data Layer & Reliability**:
- Write declarative schema definitions with foreign keys, composite indexes on queried filters, and automated timestamp triggers.
- Use connection pooling and prepared statements for serverless database execution.
---
## 5. STEP-BY-STEP SCAFFOLDING ROADMAP
- **Phase 1: Workspace & Root Config**: Initialize package manager, monorepo configuration (`turbo.json`, `tsconfig.base.json`, `package.json`).
- **Phase 2: Database Schema & Client**: Set up the data layer (PostgreSQL): client, connection pool, models, and migration scripts.
- **Phase 3: Design Tokens & UI Primitives**: Build accessible `Button`, `Input`, `Card`, `Badge`, and layout wrappers inside `packages/ui`.
- **Phase 4: Core Application Routes & Handlers**: Implement primary authentication, user session handling, and application routes.
- **Phase 5: Quality Assurance & Build Verification**: Run `tsc --noEmit`, ESLint, Prettier, and smoke test suites to ensure zero compilation or runtime errors.
---
## 6. EXECUTION INSTRUCTIONS
1. Review all specifications, architectural guardrails, and stack choices above.
2. Present the full monorepo directory tree structure.
3. Systematically generate the complete, production-ready codebase according to the 5-phase roadmap above — starting with the root workspace setup, followed by the database schema, UI design system package, and full-stack application routes until the repository is fully scaffolded and ready to run.Copied 1 time
Frequently asked about PostGraphile
What is PostGraphile built with?
PostGraphile is built in TypeScript on Node.js, utilizing PostgreSQL database introspection, the Grafast planning engine, and Graphile Build plugin pipelines.
How does PostGraphile v5 differ from earlier versions?
PostGraphile v5 is built from the ground up on Grafast, replacing classical GraphQL resolvers with operation planning graphs that compile complex nested queries into minimal SQL statements.
Does PostGraphile support web frameworks other than Express?
Yes. Through Grafserv (grafast/grafserv), PostGraphile provides first-class adapters for Fastify, Koa, Hono, Node HTTP, and serverless AWS Lambda runtimes.
How does PostGraphile handle security and permissions?
PostGraphile relies heavily on PostgreSQL native features, specifically Row-Level Security (RLS) policies, roles, and functions evaluated during transaction execution.
One email a month: new deep dives and stack trends
New source-audited architectures, head-to-head comparisons and the monthly stack report. No spam, unsubscribe anytime.
Similar architectures
- HasuraClassicInstant GraphQL Engine & Unified Data Access · 20+ peopleShares TypeScript · GraphQL · PostgreSQL
- StrapiClassicHeadless CMS · 20+ peopleShares Node.js · TypeScript · React
- TwentyHybridCRM SaaS · 6-20 peopleShares TypeScript · React · PostgreSQL
- Payload CMSHybridNext.js-Native Headless CMS & App Framework · 6-20 peopleShares TypeScript · React · GraphQL
- MedusaClassicE-commerce API · 20+ peopleShares TypeScript · Node.js · React
- ElectricSQLClassicLocal-First Sync Engine · 6-20 PeopleShares TypeScript · PostgreSQL