Skip to content

How It Works

Melange is an OpenFGA-to-PostgreSQL compiler. It reads your authorization model and compiles it into SQL functions that execute permission checks directly in your database. No external service, no network hops, no tuple synchronization.

The Compiler Model

Like Protocol Buffers compiles .proto files into language-specific serialization code, Melange compiles .fga files into PostgreSQL functions. The key difference from traditional FGA implementations is when the schema is processed:

ApproachSchema ProcessingRuntime Behavior
Traditional FGAInterpreted at query timeGeneric graph traversal
MelangeCompiled at migration timePurpose-built SQL functions

This compilation step is what enables Melange’s performance: each relation in your schema gets its own function rather than passing through a generic interpreter.

Compilation Pipeline

    flowchart LR
    subgraph Input
        schema["schema.fga<br/>(OpenFGA DSL)"]
    end

    subgraph Compiler
        melange["melange migrate"]
    end

    subgraph Output["PostgreSQL Database"]
        funcs["Specialized check functions"]
        dispatch["Dispatcher function"]
    end

    schema --> melange
    melange --> funcs
    melange --> dispatch
  

Compile Time

When you run melange migrate (or melange generate migration), the compiler:

  1. Parses your OpenFGA schema
  2. Analyzes relation patterns (direct, implied, union, intersection, etc.)
  3. Computes the transitive closure of role hierarchies
  4. Generates specialized SQL functions for each relation
  5. Installs the functions into PostgreSQL (migrate) or writes them as versioned SQL files (generate migration)

See Running Migrations for guidance on choosing between the two approaches.

Runtime

Permission checks are just SQL queries:

SELECT check_permission('user', 'alice', 'can_read', 'document', '123');
-- Returns 1 (allowed) or 0 (denied)

The generated functions query a melange_tuples view that you define over your existing domain tables. No separate tuple storage is required.

What the Compiler Generates

For a schema like:

model
  schema 1.1

type user

type folder
  relations
    define owner: [user]
    define viewer: [user] or owner

type document
  relations
    define parent: [folder]
    define owner: [user]
    define editor: [user] or owner
    define viewer: [user] or editor or viewer from parent

Melange compiles this into:

Generated FunctionPurpose
check_folder_owner()Direct tuple lookup for folder owners
check_folder_viewer()Union check: direct assignment OR implied by owner
check_document_owner()Direct tuple lookup for document owners
check_document_editor()Union check: direct assignment OR implied by owner
check_document_viewer()Complex check: direct, editor hierarchy, AND parent folder access
check_permission()Dispatcher that routes to specialized functions

A default migration also installs list (list_<type>_<relation>_obj, list_<type>_<relation>_sub), accessible_<type>_<relation>, expand_ and explain_ functions for each relation that supports them, and the matching dispatchers; melange functions lists them.

Pattern-Specific Code Generation

The compiler recognizes authorization patterns and generates code specific to each:

PatternSchema SyntaxGenerated Code
Direct assignment[user]Simple EXISTS check
Role hierarchyviewer: ownerClosure inlined as IN (...)
Union[user] or ownerOR’d EXISTS clauses
Tuple-to-usersetviewer from parentRecursive lookup via parent
Exclusionbut not blockedAccess check with exclusion
Intersectionwriter and editorAll conditions must match

Example: Compiled Function

For document.viewer: [user] or editor or viewer from parent, the compiler generates:

CREATE OR REPLACE FUNCTION check_document_viewer(
  p_subject_type TEXT,
  p_subject_id TEXT,
  p_object_id TEXT,
  p_visited TEXT[] DEFAULT ARRAY[]::TEXT[]
) RETURNS INTEGER AS $$
DECLARE
    v_key TEXT := 'document:' || p_object_id || ':viewer';
BEGIN
    -- Depth limit: 25 parent or userset hops, as in OpenFGA
    IF array_length(p_visited, 1) >= 26 THEN
        RAISE EXCEPTION 'resolution too complex' USING ERRCODE = 'M2002';
    END IF;

    -- Cycle detection for recursive patterns
    IF v_key = ANY(p_visited) THEN
        RETURN 0;
    END IF;

    -- Direct assignment or implied by editor hierarchy
    IF EXISTS(
        SELECT 1 FROM melange_tuples t
        WHERE t.object_type = 'document'
          AND t.object_id = p_object_id
          AND t.relation IN ('viewer', 'editor', 'owner')
          AND t.subject_type = p_subject_type
          AND (t.subject_id = p_subject_id OR t.subject_id = '*')
    ) THEN
        RETURN 1;
    END IF;

    -- Tuple-to-userset: viewer from parent
    IF EXISTS(
        SELECT 1 FROM melange_tuples link
        WHERE link.object_type = 'document'
          AND link.object_id = p_object_id
          AND link.relation = 'parent'
          AND check_folder_viewer(
              p_subject_type, p_subject_id,
              link.subject_id,
              p_visited || ARRAY[v_key]
          ) = 1
          AND link.subject_type IN ('folder')
    ) THEN
        RETURN 1;
    END IF;

    RETURN 0;
END;
$$ LANGUAGE plpgsql STABLE COST 1000;

Notice how the compiler has:

  • Inlined the closure ('viewer', 'editor', 'owner') rather than computing it at runtime
  • Generated pattern-specific code for tuple-to-userset traversal
  • Called check_folder_viewer directly, since parent only allows folder. A tupleset with several allowed types goes through check_permission_internal, which routes by the parent’s runtime type.
  • Added the depth limit and cycle detection for recursive patterns

The Dispatcher

check_permission() is a thin LANGUAGE sql wrapper the planner can inline. It calls check_permission_internal(), which enforces the depth limit and routes to the specialized function:

CREATE OR REPLACE FUNCTION check_permission(
  p_subject_type TEXT, p_subject_id TEXT, p_relation TEXT,
  p_object_type TEXT, p_object_id TEXT
) RETURNS INTEGER AS $$
    SELECT check_permission_internal(p_subject_type, p_subject_id, p_relation,
        p_object_type, p_object_id, ARRAY[]::TEXT[])
$$ LANGUAGE sql STABLE PARALLEL RESTRICTED;

CREATE OR REPLACE FUNCTION check_permission_internal(
  p_subject_type TEXT, p_subject_id TEXT, p_relation TEXT,
  p_object_type TEXT, p_object_id TEXT, p_visited TEXT[] DEFAULT ARRAY[]::TEXT[]
) RETURNS INTEGER AS $$
BEGIN
    IF array_length(p_visited, 1) >= 26 THEN
        RAISE EXCEPTION 'resolution too complex' USING ERRCODE = 'M2002';
    END IF;
    IF p_object_type = 'document' THEN
        IF p_relation = 'viewer' THEN
            RETURN check_document_viewer(p_subject_type, p_subject_id, p_object_id, p_visited);
        END IF;
        -- ... the other document relations
        RETURN 0;
    END IF;
    -- ... the other types
    RETURN 0;  -- unknown type/relation: deny by default
END;
$$ LANGUAGE plpgsql STABLE PARALLEL RESTRICTED COST 1000;

When the sql section of melange.yaml leaves a relation out, check_permission raises SQLSTATE M2003 for it instead of returning 0.

This eliminates runtime schema interpretation and allows PostgreSQL’s query planner to optimize each specialized function independently.

Precomputed Relation Closure

Role hierarchies are resolved at compile time, not runtime. For a schema with:

define owner: [user]
define admin: [user] or owner
define member: [user] or admin

The compiler precomputes the transitive closure:

relationsatisfying_relation
membermember
memberadmin
memberowner
adminadmin
adminowner
ownerowner

This closure is inlined directly into the generated SQL. Checking “does user have member?” becomes a simple IN ('member', 'admin', 'owner') clause rather than recursive function calls.

The melange_tuples View

Melange reads authorization data from a view you define over your existing tables:

CREATE VIEW melange_tuples AS
-- Team memberships
SELECT 'user' AS subject_type,
       user_id::text AS subject_id,
       role AS relation,
       'folder' AS object_type,
       folder_id::text AS object_id
FROM folder_members

UNION ALL

-- Document -> Folder relationship
SELECT 'folder' AS subject_type,
       folder_id::text AS subject_id,
       'parent' AS relation,
       'document' AS object_type,
       id::text AS object_id
FROM documents;

This approach means:

  • Zero tuple sync: No separate tuple storage to maintain
  • Transaction awareness: Permission checks see uncommitted changes
  • Real-time consistency: Tuples always reflect current database state

See Tuples View for detailed guidance on mapping your domain tables.

OpenFGA Compatibility

Melange provides full OpenFGA Schema 1.1 compatibility (excluding conditions). The same .fga schema files work with both Melange and OpenFGA, continuously validated against the official OpenFGA test suite.

Performance

A permission check is one SQL call. On a managed PostgreSQL instance, measured from an application VM in the same zone, a check spends about 0.1 ms in the database and takes about 0.4 to 0.7 ms end to end, most of it the network round trip. Check latency stayed roughly flat across the measured fixtures, from thousands to two million tuples. This is a measured workload result, not a constant-time guarantee: recursive relations can still require traversal, and graph depth, fan-out, and indexes matter. List operations cost more: they grow with the part of the permission graph they walk.

Summary

Melange’s compiler architecture has four key properties:

  1. Compile-time specialization: A dedicated SQL function for each relation
  2. Precomputed closure: Role hierarchies resolved before runtime
  3. View-based tuples: Direct queries against your existing tables
  4. Native SQL execution: Uses PostgreSQL’s query optimizer

The measured kitchen-sink checks spend about 0.06 to 0.13 ms in the database, with OpenFGA Schema 1.1 compatibility (excluding conditions), without requiring a separate authorization service.