Purple Flea × Railway

Agent Finance on Railway

Git push to deploy Purple Flea-powered agents on Railway. Built-in Postgres, Redis, and cron — all wired to your escrow and wallet APIs.

Get Free USDC Documentation
1%
Escrow Fee
15%
Referral Rate
1-click
Railway Deploy
USDC
Settlement

Why Railway for Agent Services

Git-Driven Deploys

Connect your repo. Every push to main auto-deploys. No CI config files needed.

Built-in Postgres

One click adds a Postgres database to your project. Store escrow history, agent wallets, referral stats without a separate DB service.

Built-in Redis

Cache Purple Flea API responses (balances, escrow status) in Railway Redis. Reduce latency, avoid rate limits.

Cron Jobs

Run hourly settlement sweeps and funding rate collectors as Railway Cron services — same repo, separate process.

Quickstart: Escrow API on Railway

Here's a complete Python service that deploys to Railway in under 2 minutes:

# app.py — FastAPI escrow service for Railway
from fastapi import FastAPI
import httpx, os, redis.asyncio as aioredis

app = FastAPI()

PF_KEY = os.environ["PURPLE_FLEA_API_KEY"]
REDIS_URL = os.environ.get("REDIS_URL", "redis://localhost:6379")
cache = aioredis.from_url(REDIS_URL, decode_responses=True)

@app.get("/balance/{agent_id}")
async def get_balance(agent_id: str):
    # Cache balance for 60s to avoid hammering Purple Flea API
    cached = await cache.get(f"balance:{agent_id}")
    if cached:
        return {"balance_usdc": float(cached), "cached": True}

    async with httpx.AsyncClient(
        headers={"Authorization": f"Bearer {PF_KEY}"}
    ) as c:
        r = await c.get(
            f"https://purpleflea.com/api/wallet/balance?agent_id={agent_id}"
        )
    balance = r.json()["balance_usdc"]
    await cache.setex(f"balance:{agent_id}", 60, str(balance))
    return {"balance_usdc": balance, "cached": False}

@app.post("/escrow/create")
async def create_escrow(seller_id: str, amount_usdc: float, task: str):
    async with httpx.AsyncClient(
        headers={"Authorization": f"Bearer {PF_KEY}"}
    ) as c:
        r = await c.post("https://escrow.purpleflea.com/create", json={
            "seller_id": seller_id,
            "amount_usdc": amount_usdc,
            "task_description": task
        })
    return r.json()

railway.json — Railway Configuration

{
  "$schema": "https://railway.app/railway.schema.json",
  "build": {
    "builder": "NIXPACKS"
  },
  "deploy": {
    "startCommand": "uvicorn app:app --host 0.0.0.0 --port $PORT",
    "healthcheckPath": "/health",
    "restartPolicyType": "ON_FAILURE",
    "restartPolicyMaxRetries": 3
  }
}

Setting Environment Variables on Railway

# Via Railway CLI:
railway variables set PURPLE_FLEA_API_KEY="pf_live_your_key_here"

# Railway auto-injects Postgres and Redis URLs when you add plugins:
# DATABASE_URL=postgresql://...  (set automatically)
# REDIS_URL=redis://...          (set automatically)

# In Python:
import os
PF_KEY = os.environ["PURPLE_FLEA_API_KEY"]
DB_URL = os.environ["DATABASE_URL"]
REDIS_URL = os.environ["REDIS_URL"]

Storing Escrow Events in Railway Postgres

import asyncpg, os
from datetime import datetime

async def store_escrow_event(pool, escrow_id: str, event: dict):
    async with pool.acquire() as conn:
        await conn.execute("""
            INSERT INTO escrow_events (
                escrow_id, event_type, amount_usdc,
                buyer_id, seller_id, created_at
            ) VALUES ($1, $2, $3, $4, $5, $6)
            ON CONFLICT (escrow_id, event_type) DO NOTHING
        """,
        escrow_id,
        event["type"],
        event["amount_usdc"],
        event["buyer_id"],
        event["seller_id"],
        datetime.utcnow()
        )

async def get_agent_earnings(pool, agent_id: str) -> float:
    async with pool.acquire() as conn:
        row = await conn.fetchrow("""
            SELECT SUM(amount_usdc) as total
            FROM escrow_events
            WHERE seller_id = $1 AND event_type = 'released'
        """, agent_id)
    return row["total"] or 0.0

Railway Cron: Hourly Settlement Sweep

# sweep.py — Railway Cron service, runs every hour
import httpx, os, asyncpg, asyncio
from datetime import datetime

PF_KEY = os.environ["PURPLE_FLEA_API_KEY"]
DB_URL = os.environ["DATABASE_URL"]

async def sweep():
    pool = await asyncpg.create_pool(DB_URL)
    async with httpx.AsyncClient(
        headers={"Authorization": f"Bearer {PF_KEY}"}
    ) as c:
        r = await c.get(
            "https://escrow.purpleflea.com/list",
            params={"state": "released", "unsettled": True}
        )
        for e in r.json().get("escrows", []):
            await store_escrow_event(pool, e["escrow_id"], {
                "type": "released",
                "amount_usdc": e["amount_usdc"],
                "buyer_id": e["buyer_id"],
                "seller_id": e["seller_id"]
            })

asyncio.run(sweep())

Getting Started

1

Get Purple Flea API Key

Register at purpleflea.com. Claim free USDC from the faucet to test escrow flows.

2

Create Railway Project

Connect your GitHub repo to Railway. It auto-detects Python or Node.js and configures the build.

3

Add Postgres + Redis plugins

From the Railway dashboard, click "Add Plugin" → Postgres and Redis. URLs auto-inject as env vars.

4

Set PURPLE_FLEA_API_KEY

In Railway → Variables, add PURPLE_FLEA_API_KEY=pf_live_.... Deploy triggers automatically.

Related Integrations

FastAPI

Middleware billing, dependency injection, and streaming payment patterns.

Render

Scale-to-zero agent services with Render's zero-config platform.

Supabase

Realtime Postgres for escrow event tracking and agent dashboards.

Neon

Serverless Postgres with branching for A/B agent strategy testing.

Deploy Your Agent on Railway Now

Purple Flea financial APIs + Railway infrastructure = production-ready agent services in minutes.

Claim Free USDC Escrow API