Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Cloudflare platform skill covering Workers, D1, R2, KV, AI, Durable Objects, and security.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/smart-placement/api.md
1# Smart Placement API23## Placement Status API45Query Worker placement status via Cloudflare API:67```bash8curl -X GET "https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/workers/services/{WORKER_NAME}" \9-H "Authorization: Bearer <TOKEN>" \10-H "Content-Type: application/json"11```1213Response includes `placement_status` field:1415```typescript16type PlacementStatus =17| undefined // Not yet analyzed18| 'SUCCESS' // Successfully optimized19| 'INSUFFICIENT_INVOCATIONS' // Not enough traffic20| 'UNSUPPORTED_APPLICATION'; // Made Worker slower (reverted)21```2223## Status Meanings2425**`undefined` (not present)**26- Worker not yet analyzed27- Always runs at default edge location closest to user2829**`SUCCESS`**30- Analysis complete, Smart Placement active31- Worker runs in optimal location (may be edge or remote)3233**`INSUFFICIENT_INVOCATIONS`**34- Not enough requests to make placement decision35- Requires consistent multi-region traffic36- Always runs at default edge location3738**`UNSUPPORTED_APPLICATION`** (rare, <1% of Workers)39- Smart Placement made Worker slower40- Placement decision reverted41- Always runs at edge location42- Won't be re-analyzed until redeployed4344## cf-placement Header (Beta)4546Smart Placement adds response header indicating routing decision:4748```typescript49// Remote placement (Smart Placement routed request)50"cf-placement: remote-LHR" // Routed to London5152// Local placement (default edge routing)53"cf-placement: local-EWR" // Stayed at Newark edge54```5556Format: `{placement-type}-{IATA-code}`57- `remote-*` = Smart Placement routed to remote location58- `local-*` = Stayed at default edge location59- IATA code = nearest airport to data center6061**Warning:** Beta feature, may be removed before GA.6263## Detecting Smart Placement in Code6465**Note:** `cf-placement` header is a beta feature and may change or be removed.6667```typescript68export default {69async fetch(request: Request, env: Env): Promise<Response> {70const placementHeader = request.headers.get('cf-placement');7172if (placementHeader?.startsWith('remote-')) {73const location = placementHeader.split('-')[1];74console.log(`Smart Placement routed to ${location}`);75} else if (placementHeader?.startsWith('local-')) {76const location = placementHeader.split('-')[1];77console.log(`Running at edge location ${location}`);78}7980return new Response('OK');81}82} satisfies ExportedHandler<Env>;83```8485## Request Duration Metrics8687Available in Cloudflare dashboard when Smart Placement enabled:8889**Workers & Pages → [Your Worker] → Metrics → Request Duration**9091Shows histogram comparing:92- Request duration WITH Smart Placement (99% of traffic)93- Request duration WITHOUT Smart Placement (1% baseline)9495**Request Duration vs Execution Duration:**96- **Request duration:** Total time from request arrival to response delivery (includes network latency)97- **Execution duration:** Time Worker code actively executing (excludes network waits)9899Use request duration to measure Smart Placement impact.100101### Interpreting Metrics102103| Metric Comparison | Interpretation | Action |104|-------------------|----------------|--------|105| WITH < WITHOUT | Smart Placement helping | Keep enabled |106| WITH ≈ WITHOUT | Neutral impact | Consider disabling to free resources |107| WITH > WITHOUT | Smart Placement hurting | Disable with `mode: "off"` |108109**Why Smart Placement might hurt performance:**110- Worker primarily serves static assets or cached content111- Backend services are globally distributed (no single optimal location)112- Worker has minimal backend communication113- Using Pages with `assets.run_worker_first = true`114115**Typical improvements when Smart Placement helps:**116- 20-50% reduction in request duration for database-heavy Workers117- 30-60% reduction for Workers making multiple backend API calls118- Larger improvements when backend is geographically concentrated119120## Monitoring Commands121122```bash123# Tail Worker logs124wrangler tail your-worker-name125126# Tail with filters127wrangler tail your-worker-name --status error128wrangler tail your-worker-name --header cf-placement129130# Check placement status via API131curl -H "Authorization: Bearer $TOKEN" \132https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/workers/services/$WORKER_NAME \133| jq .result.placement_status134```135136## TypeScript Types137138```typescript139// Placement status returned by API (field may be absent)140type PlacementStatus =141| 'SUCCESS'142| 'INSUFFICIENT_INVOCATIONS'143| 'UNSUPPORTED_APPLICATION'144| undefined;145146// Placement configuration in wrangler.jsonc147type PlacementMode = 'smart' | 'off';148149interface PlacementConfig {150mode: PlacementMode;151// Legacy fields (deprecated/removed):152// hint?: string; // REMOVED - no longer supported153}154155// Explicit placement (separate feature from Smart Placement)156interface ExplicitPlacementConfig {157region?: string;158host?: string;159hostname?: string;160// Cannot combine with mode field161}162163// Worker metadata from API response164interface WorkerMetadata {165placement?: PlacementConfig | ExplicitPlacementConfig;166placement_status?: PlacementStatus;167}168169// Service Binding for backend Worker170interface Env {171BACKEND_SERVICE: Fetcher; // Service Binding to backend Worker172DATABASE: D1Database;173}174175// Example Worker with Service Binding176export default {177async fetch(request: Request, env: Env): Promise<Response> {178// Forward to backend Worker with Smart Placement enabled179const response = await env.BACKEND_SERVICE.fetch(request);180return response;181}182} satisfies ExportedHandler<Env>;183```184