# Conflicts: # .github/workflows/check-insights-major-version.yml # .github/workflows/check-posthog-major-version.yml # .github/workflows/ci-security.yaml # .github/workflows/validate-versioning.yml # AGENTS.md # AGENTS.md~upstream_main # packages/ai/src/otel/capture.ts # packages/ai/src/otel/mappers/aiSdk.ts # packages/ai/src/otel/mappers/index.ts # packages/ai/src/otel/types.ts # packages/core/src/__tests__/posthog.init.spec.ts # packages/react-native/src/PostHogProvider.tsx # packages/react/src/context/PostHogContext.ts # packages/react/src/context/PostHogProvider.tsx # tooling/eslint-plugin-insights/no-unsafe-web-global.js
Insights Cloudflare KV Cache Example
This example demonstrates how to implement a distributed cache for Insights feature flag definitions using Cloudflare KV storage. It showcases a split read/write pattern optimized for edge workers where low-latency flag evaluation is critical.
Architecture
The example uses two specialized cache implementations:
CloudflareKVFlagCacheReader- Read-only cache used in request handlers to evaluate flags locally without API callsCloudflareKVFlagCacheWriter- Write-only cache used in scheduled jobs to periodically refresh flag definitions
How It Works
- A Cloudflare Worker scheduled job (cron) runs every 5 minutes
- The scheduled job fetches fresh flag definitions from Insights and stores them in Cloudflare KV
- Request handlers read flag definitions from KV and evaluate flags locally
- No API calls are made during request handling, ensuring minimal latency
This pattern is ideal for high-traffic edge applications where:
- Flag evaluation must be extremely fast
- You want to minimize API calls to Insights
- You can tolerate flag updates being slightly delayed (up to 5 minutes, or your own cron schedule)
Prerequisites
- Node.js and pnpm installed
- A Insights account with a project API key and personal API key
Setup
1. Build Local Dependencies
From the root of the @hanzo/insights repository:
pnpm i
pnpm package
2. Configure Environment Variables
Copy the example environment file and fill in your Insights credentials:
cp .env.example .env
Edit .env and set:
INSIGHTS_PROJECT_API_KEY=your_project_api_key
INSIGHTS_PERSONAL_API_KEY=your_insights_personal_api_key
INSIGHTS_HOST=https://us.i.insights.hanzo.ai
3. Build the Example
pnpm build
Running Locally
Start the Cloudflare Worker
pnpm dev
Trigger the Scheduled Job
Manually trigger the cache update to populate flag definitions:
curl http://127.0.0.1:8788/cdn-cgi/handler/scheduled
Expected response:
ok
Test Flag Evaluation
Request the worker endpoint to evaluate a flag locally:
curl http://127.0.0.1:8787
Expected response:
{ "userId": "wvhqg4goolm", "feature": "beta-feature", "enabled": true }
The userId will be randomly generated for each request, and enabled will depend on your flag configuration in Insights.