FolioFOLIOdocs
AppApp
BackendBackend
Backend/API Layer
03 / 07

API Layer

The glue between things

Edge FunctionsAlpha VantageClaude

Overview

The API layer is a set of 6 Supabase Edge Functions that sit between the app and external services. The market_data function proxies Alpha Vantage calls to keep the API key secret and adds server side caching plus per user rate limiting. The assistant function connects to Claude with tool use for fetching real time quotes and news mid conversation. Three scheduled functions handle alerts, maturity reminders, and daily digests. And portfolio_insights generates quick or detailed AI analysis of your holdings.

How it works

1

The market_data edge function is the busiest one. The client POSTs the Alpha Vantage function name and params. The edge function appends the API key, forwards the request, and caches the response in memory with a configurable TTL (default 60 seconds). It also rate limits at 60 requests per minute per user, extracting the user ID from the JWT. If the same warm instance handles the request, cached results come back instantly with an X-Cache: HIT header.

2

The assistant function implements a tool use loop. It defines two tools: get_market_news and get_asset_quote. When Claude needs live data to answer a question, it calls a tool, the edge function executes it against Alpha Vantage, and feeds the result back. This loop runs up to 5 iterations before returning. The function also supports vision for the screenshot import feature.

3

The check_alerts function runs on a schedule. It fetches all active, non triggered alerts from the database, groups them by symbol to minimize API calls, fetches current prices (with 200ms delays between calls to respect rate limits), evaluates each alert condition, and sends Expo push notifications to triggered users. It also deactivates push tokens that come back as DeviceNotRegistered.

4

The daily_digest function is timezone aware. It checks each user's preferred digest hour against their timezone, fetches their top 5 holdings and relevant news from Alpha Vantage, generates a personalized briefing with Claude, and sends it as a push notification. The full briefing text rides along in the notification data payload so the app can display it without another API call. It deduplicates by checking the notification_log to avoid sending twice in one day.

5

The check_maturity function looks for fixed income assets approaching their maturity date. It checks against reminder thresholds (30, 7, 1, and 0 days out) and sends reminders based on user preferences. One notification per asset per day.

6

The portfolio_insights function takes a portfolio snapshot and generates either a quick insight (one liner, 256 tokens) or a detailed analysis (full JSON with diversification score, strengths, risks, and suggestions at 1024 tokens). Both modes use Claude Sonnet.

Key decisions

Edge functions as an API proxy, not a full backend

We do not have a traditional REST API with controllers and routes. The client talks directly to Supabase for CRUD (reads, writes, sync) and only uses edge functions when we need to call external services or run scheduled jobs. This keeps the architecture simple. Supabase handles the boring stuff (CRUD, auth, realtime), and edge functions handle the interesting stuff (AI, market data, notifications).

In memory caching on the edge function

The market_data function caches responses in a JavaScript Map. This only works within a single warm instance, and it resets on cold starts. But during active usage, the same instance handles many requests, and the cache prevents hammering Alpha Vantage. A proper Redis cache would be more reliable, but for our usage patterns this is good enough and adds zero infrastructure.

Tool use loop in the assistant

The assistant does not just generate text. It can call tools mid conversation to fetch live stock prices and news. The loop cap at 5 iterations prevents runaway tool calls. This makes the AI responses actually useful because they reference real time data instead of guessing from training data. The tradeoff is higher latency (each tool call adds a round trip), but the accuracy is worth it.

Grouping alerts by symbol

If 50 users have alerts for AAPL, we only fetch the AAPL price once instead of 50 times. The check_alerts function groups all alerts by symbol, fetches each price once, then evaluates all alerts for that symbol. This reduces API calls dramatically and keeps us well within Alpha Vantage rate limits.

EdgeFunctionsAlphaVantageClaudeAIExpoPushSupabaseDBCacheClientApp

Quick Reference

Filessupabase/functions/*, services/alphaVantage/client.ts, hooks/queries/*
Tablesalerts, notification_log, push_tokens, user_preferences
Edge Functionsmarket-data, assistant, check-alerts, check-maturity, daily-digest, portfolio-insights
Components
AlphaVantageClientuseBulkQuotesuseMultiAssetQuotesuseMarketNewsuseAssetSearch
PreviousDatabaseNextSubscriptions