[{"content":"Running a self-hosted E2B cluster is about more than getting Firecracker sandboxes to start. We also need to consider how to keep them stable once they host long-running workloads. As a single cluster supports more sandboxes, resilience becomes increasingly important. Our architecture needs to protect existing runtime state and user connections while limiting the impact on capacity for new sandboxes, so that a local interruption does not cause unnecessary disruption elsewhere.\nThis article starts with a single Nomad server becoming unavailable. It describes what we learned about Server / Client heartbeats and the changes we explored to task preservation, node failure detection, and blast-radius control.\nIn this self-hosted environment, three Nomad servers form the control plane. The failure affected only the VM hosting one of them; the Clients running sandboxes and the other nodes remained healthy. Our initial expectation was straightforward: the remaining servers would keep the control plane available, Clients would switch to another healthy server, and workloads would continue running.\nThe tests revealed something counterintuitive: only one server was lost, yet Orchestrator and other tasks on healthy Nomad Client hosts were replaced. To understand why, we first needed to examine how Nomad servers and Clients use heartbeats to maintain contact, and what Nomad does with existing tasks when those heartbeats stop arriving.\nHow a Single Server Failure Affects an E2B Deployment First, consider the relationship between E2B and Nomad. In this deployment, Nomad schedules and manages services such as the API, Orchestrator, session-proxy, and client-proxy. Orchestrator, in turn, manages Firecracker sandboxes on its host. Sandbox creation and state management are handled by Orchestrator instances deployed on sandbox nodes and managed by Nomad.\nflowchart TB accTitle: Control and access paths in self-hosted E2B accDescr: Nomad manages infrastructure services, while Orchestrator manages sandboxes. Sandbox traffic does not pass through Nomad servers for every request. servers[\"3 x Nomad serversLeader / Follower\"] subgraph host[\"Sandbox host\"] agent[\"Nomad Client agent\"] orchestrator[\"Orchestrator\"] proxy[\"session-proxy\"] sandboxes[\"Firecracker sandboxesOriginal processes / memory / files\"] agent --\u003e|\"Run tasks\"| orchestrator agent --\u003e|\"Run tasks\"| proxy orchestrator --\u003e|\"Create and manage\"| sandboxes proxy --\u003e|\"Forward workload requests\"| sandboxes end agent -.-\u003e|\"Node.UpdateStatus\"| servers servers -.-\u003e|\"Heartbeat response / allocation state\"| agent user[\"E2B SDK / user\"] --\u003e entry[\"client-proxyShared proxy entry point\"] entry --\u003e proxyA Nomad Client is the agent running on a host. It communicates with servers and executes tasks. When Nomad schedules a task group onto a Client node, the resulting execution instance is called an allocation.\nTo observe whether a single server failure could trigger task replacement, we forcibly stopped one non-Leader server without configuring a disconnect retention policy. The other two servers maintained quorum, and we continued observing for approximately 11 minutes.\nTracking the identities of the original allocations, we recorded the following replacements for selected tasks:\nTask Original allocations replaced / original total Orchestrator 7 / 20 session-proxy 7 / 20 client-proxy 2 / 3 The experiment showed that the control plane can instruct a Client to abandon its original tasks even when the Client host has neither failed nor restarted.\nFor an E2B cluster, this is an important detail. Orchestrator manages sandbox runtime resources and participates in sandbox creation and state management. An unnecessary replacement can therefore affect sandboxes that are already running.\nThe Unexpected Sequence: Tasks Stop After Heartbeats Recover Using the platform\u0026rsquo;s confirmation that the server had stopped as the observation baseline, we aligned Nomad Client logs with workload events:\nAt approximately 21 seconds, we had captured a successful heartbeat from the Client to a healthy server. At approximately 39 seconds, the original task began Killing. At approximately 44 seconds, the original application stream closed. The node and allocation states showed that the Client executed a previously made stop decision only after reconnecting and receiving an update. The overall sequence was:\n1 2 3 4 5 6 Heartbeat expires -\u0026gt; Server updates node status and triggers a scheduling evaluation -\u0026gt; Scheduler marks the original allocation as stop / lost -\u0026gt; Client reconnects and retrieves the allocation update -\u0026gt; Local task executes Killing -\u0026gt; Replacement allocation starts Understanding Nomad Heartbeats: How Node Failure Detection Affects Workloads With this question in mind, we examined Nomad\u0026rsquo;s GitHub source code and official documentation. We traced the following call chain:\nClient sends a heartbeat -\u0026gt; RPC selects a server -\u0026gt; Follower forwards the request -\u0026gt; Leader renews the heartbeat timer -\u0026gt; Expiration updates node status -\u0026gt; Scheduler processes allocations -\u0026gt; Client applies task updates.\nThe sequence diagram below provides the full picture before we walk through the code. Its timestamps are illustrative and start from the last successfully processed heartbeat at the Leader. The log timestamps above start from the platform\u0026rsquo;s stop confirmation, so the two timelines do not correspond directly.\nsequenceDiagram accTitle: From heartbeat expiration to termination of the original task accDescr: t=0 is the last successful heartbeat at the Leader. With an illustrative TTL of 15 seconds and grace of 10 seconds, expiration occurs at about 25 seconds. If connectivity returns at 40 seconds, the Client can still execute a stop plan created earlier. These are illustrative, not measured, timestamps. autonumber participant Time as Relative timeline participant C as Nomad Client participant F as Follower participant L as Leader participant S as Scheduler participant T as Original task Note over C,T: Illustrative: TTL=15s, grace=10st=0: last successful heartbeat at LeaderNot measured or to scale, scheduling delay omitted Note over Time: 0sLast successful heartbeat C-\u003e\u003eF: Node.UpdateStatus F-\u003e\u003eL: t=0: Forward heartbeat and renew timer L--\u003e\u003eF: Return dynamic TTL=15s F--\u003e\u003eC: Heartbeat succeeds Note over Time: 5s Note over F: t=5s: Assume the server VM becomes unavailable Note over Time: About 15s C-xF: t~15s: Next heartbeat RPC does not return promptly Note over Time: About 25s15s TTL + 10s grace Note over L: t~25s (15+10): Heartbeat budget expires L-\u003e\u003eL: Update node status L-\u003e\u003eS: Trigger node-update evaluation Note over Time: About 25s+ S-\u003e\u003eL: t~25s+: Submit stop plan for original allocation Note over Time: 40sAssumed recovery point C-\u003e\u003eL: t=40s: Assume heartbeat succeeds through a healthy server C-\u003e\u003eL: Retrieve allocation updates L--\u003e\u003eC: Original allocation is already marked to stop Note over Time: 40s+ C-\u003e\u003eT: t=40s+: Local runner executes Killing Note over C,T: The stop plan predates reconnectionA recovered heartbeat does not automatically cancel itThe following sections walk through the key code paths. The snippets have been simplified.\n1. Client Heartbeats Report Node Status On the Client, registerAndHeartbeat() handles registration and periodic heartbeats. The actual request is constructed in updateNodeStatus():\n1 2 3 4 5 6 7 8 9 req := structs.NodeUpdateStatusRequest{ NodeID: c.NodeID(), Status: structs.NodeStatusReady, } var resp structs.NodeUpdateResponse if err := c.RPC(\u0026#34;Node.UpdateStatus\u0026#34;, \u0026amp;req, \u0026amp;resp); err != nil { return err } c.heartbeatTTL = resp.HeartbeatTTL The request reports the NodeID and node status, not the application health of a particular Job. After a successful response, the Client uses HeartbeatTTL to schedule its next heartbeat. After a failure, the heartbeat loop schedules a retry and triggers server discovery.\nMultiple tasks on the same Client therefore share the node heartbeat. Node.UpdateAlloc reports allocation state, while Orchestrator\u0026rsquo;s gRPC health check measures application health. Neither replaces this Client-to-Server heartbeat.\n2. One Server per RPC Attempt: Switching Paths Waits for the Call to Return Next, consider the Client\u0026rsquo;s rpc(). The key sequence, simplified, is:\n1 2 3 4 5 server := c.servers.FindServer() rpcErr := c.connPool.RPC(c.Region(), server.Addr, method, args, reply) if rpcErr != nil { c.servers.NotifyFailedServer(server) } The Client first selects a server and then makes the RPC through the connection pool. Only after the current call returns an error does it report the server failure and decide whether to retry at the RPC layer, based on the error type and remaining budget. If the error is not safe to retry automatically, it returns to the heartbeat loop above.\nThe important delay here is how long it takes an RPC to return an error after a connection fails. Under the default configuration and yamux implementation, when an established connection silently fails, the Keepalive interval is 30 seconds, and a Ping waits approximately 10 seconds for a Pong. Assuming the Ping write does not block and no Ping was already in flight before the failure, detecting the failure can take roughly 10-40 seconds, depending on the Keepalive phase.\nThe retry budget is also checked only after the underlying call returns; it cannot interrupt that call early. This creates a possible race: the connection is still waiting to confirm a failure while the Leader\u0026rsquo;s node heartbeat budget has already expired.\n3. Heartbeats Can Pass Through a Follower, but the Leader Renews the Timer When a server receives the request, it first passes through the forwarding check in Node.UpdateStatus():\n1 2 3 if done, err := n.srv.forward(\u0026#34;Node.UpdateStatus\u0026#34;, args, args, reply); done { return err } forward() determines whether the current server should handle the request. If it is not the Leader, it forwards the request to the Leader.\nThe Client does not need to contact the Leader directly every time, but its selected first-hop server must deliver the request promptly. If the Follower stops responding and the Client cannot switch paths in time, a healthy Leader may still fail to receive that Client\u0026rsquo;s heartbeat.\n4. The Leader Waits for the Dynamic TTL Plus Grace Once the heartbeat successfully reaches the Leader, it calls resetHeartbeatTimer(). The function calculates an interval based on cluster size and then adds random jitter:\n1 2 3 4 5 6 7 8 ttl := helper.RateScaledInterval( h.srv.config.MaxHeartbeatsPerSecond, h.srv.config.MinHeartbeatTTL, len(h.heartbeatTimers), ) ttl += helper.RandomStagger(ttl) h.resetHeartbeatTimerLocked(id, ttl+h.srv.config.HeartbeatGrace) return ttl, nil The returned ttl determines the Client\u0026rsquo;s next heartbeat interval, while the Leader sets its expiration timer to ttl + HeartbeatGrace. heartbeat_grace adds time for the Server to wait for the next successful heartbeat.\nFollowing the official heartbeat documentation, the normal path can be understood as:\n1 2 3 4 Reference node expiration time = Time when the Leader last successfully processed a heartbeat and reset its timer + Dynamic heartbeat TTL for that round + heartbeat_grace In this small cluster, the normal TTL was approximately 10-20 seconds. With the default 10-second grace, the Leader\u0026rsquo;s budget before declaring a Client\u0026rsquo;s heartbeat expired was approximately 20-30 seconds.\n5. Timer Expiration Changes Node Status Before Triggering Scheduling When the timer expires, the Leader runs invalidateHeartbeat(). The key node-status branch is:\n1 2 3 4 req.Status = structs.NodeStatusDown if canDisconnect \u0026amp;\u0026amp; hasPendingReconnects { req.Status = structs.NodeStatusDisconnected } Whether the node enters disconnected depends on whether its allocations support reconnection and remain within their recovery windows. Not every heartbeat expiration leads to the same state transition.\nThe node-status update path then persists the necessary state changes through Raft and creates scheduling evaluations for the relevant transitions. The scheduler uses the Job type and disconnect policy to decide which allocations to retain temporarily, which to mark lost, and whether to create replacements.\nFor example, stop calculations for service allocations handle the lost set, while the node reconciliation logic for system Jobs distinguishes reconnectable unknown allocations from those that need to be treated as lost.\nA heartbeat timeout does not mean the Leader directly sends a kill signal to an application process. Node-status updates and scheduling plans sit between those events, and that is where the following configuration changes can intervene.\n6. After Reconnecting, the Client Applies an Allocation Update That Already Exists The Client retrieves server-side allocation changes through watchAllocations(). Once an update reaches the local runner, handleAllocUpdate() checks whether the allocation is transitioning to a terminal state:\n1 2 3 4 5 stopping := !ar.Alloc().TerminalStatus() \u0026amp;\u0026amp; update.TerminalStatus() ar.setAlloc(update) if stopping { ar.killTasks() } The terminal-state check also includes the Server\u0026rsquo;s desired state. Even if the original task is still running, the local runner stops it if the received update already requires termination.\nThis connects the cause and effect seen in the logs: the Client did not switch heartbeat paths before its budget expired, so the Server updated node status and the scheduler created a stop plan. When the Client later reconnected, it applied the update and stopped the original task. Replacement means a new allocation starts, not that a task restarts within the original allocation.\nThe community has also discussed similar symptoms in hashicorp/nomad#17974.\nUnderstanding this chain reveals two intervention points: allow more time to switch heartbeat paths before declaring a node disconnected, or give the original tasks a chance to reconnect after that declaration.\nSolution 1: Preserve Original Tasks and Access Paths with disconnect For E2B, the first priority is to avoid unnecessarily replacing Orchestrator on a healthy Client because of a brief control-plane disconnection.\nWe used Nomad\u0026rsquo;s disconnect policy to separate \u0026ldquo;detect that the node is disconnected\u0026rdquo; from \u0026ldquo;immediately abandon its original tasks.\u0026rdquo; The configuration belongs in an existing Job\u0026rsquo;s task group, for example:\n1 2 3 4 5 6 7 8 9 group \u0026#34;orchestrator\u0026#34; { disconnect { lost_after = \u0026#34;50s\u0026#34; replace = false reconcile = \u0026#34;keep_original\u0026#34; } # Keep the existing task, network, and other definitions unchanged. } Orchestrator, session-proxy, and client-proxy should each be evaluated and configured in their respective groups where protection is needed.\nSetting What it addresses lost_after = \u0026quot;50s\u0026quot; Provides a bounded reconnection window after an allocation enters unknown replace = false Prevents immediate replacement during the disconnect retention phase reconcile = \u0026quot;keep_original\u0026quot; Prefers the original instance during applicable reconnection reconciliation Explicitly setting replace = false prevents an immediate replacement from being created within the retention window. The corresponding scheduler check is:\n1 2 3 if isDisconnecting \u0026amp;\u0026amp; !alloc.ReplaceOnDisconnect() { return } The other distinction is when the window starts. Allocation.Expired() calculates expiration from the allocation\u0026rsquo;s most recent transition into unknown:\n1 2 3 lastUnknown := a.LastUnknown() expiry := lastUnknown.Add(tg.GetDisconnectLostAfter()) return expiry.Sub(now) \u0026lt;= 0 Therefore, lost_after = \u0026quot;50s\u0026quot; does not mean waiting 50 seconds from the server\u0026rsquo;s failure, and it is not equivalent to heartbeat_grace = \u0026quot;50s\u0026quot;. Assuming a TTL of 15 seconds and a grace of 10 seconds, the approximate sequence is:\n1 2 3 4 t = 0 Last successful heartbeat at the Leader t ~ 25s Heartbeat expires; node disconnection handling begins t ~ 25s+ Relevant allocation enters unknown t ~ (25+50)=75s+ If recovery has not completed, the 50-second retention window expires disconnect Sequence: Retain the Original Task, Then Wait for Reconnection The following diagram assumes that the original task on a healthy Client is still running. It shows how the 50s / false / keep_original policy handles a brief disconnection:\nsequenceDiagram accTitle: How disconnect retains the original task after node disconnection accDescr: t=0 is the last successful heartbeat. With an illustrative TTL of 15 seconds and grace of 10 seconds, expiration occurs at about 25 seconds. A separate 50-second window starts when the allocation enters unknown. The example either reconnects at 40 seconds or proceeds to expiration handling after approximately 75 seconds. These are not measured timestamps. autonumber participant Time as Relative timeline participant C as Nomad Client participant L as Leader participant S as Scheduler participant T as Original task Note over C,T: Illustrative: TTL=15s, grace=10s, lost_after=50st=0: last successful heartbeat at LeaderNot measured or to scale, scheduling delay omitted Note over Time: 0sLast successful heartbeat C-\u003e\u003eL: t=0: Last successful heartbeat through a server L--\u003e\u003eC: Return dynamic TTL=15s Note over Time: 5s Note over C,L: t=5s: Assume the original first-hop server fails Note over Time: About 15s C-xL: t~15s: Heartbeat through the original path does not succeed Note over Time: About 25sHeartbeat budget expires Note over L: t~25s (15+10): Heartbeat budget expires L-\u003e\u003eL: Mark node as disconnected L-\u003e\u003eS: Trigger scheduling evaluation Note over Time: tU ~ 25s+Retention window starts S-\u003e\u003eL: tU~25s+: Mark original allocation as unknown Note over L,S: Start a separate 50s window at tUExpiration: tU+50s~75s+ Note over S,T: replace = false: No immediate replacement Note over T: Original task keeps running on the healthy host alt Assume connectivity returns at t=40s within the window Note over Time: 40sStill within the retention window C-\u003e\u003eL: Restore heartbeat through another healthy server C-\u003e\u003eL: Synchronize original allocation runtime state L-\u003e\u003eS: Trigger reconnection reconciliation S-\u003e\u003eL: Retain original instance under keep_original Note over T: t=40s+: Preserve task identity without a disconnection-induced restart else Still disconnected at tU+50s~75s+ Note over Time: tU + 50s ~ 75s+Retention window expires S-\u003e\u003eL: Window expires, proceed to lost and subsequent recovery endThis does not extend the node\u0026rsquo;s heartbeat budget. Instead, it delays the decision to abandon the original allocation: enter unknown, avoid immediate replacement, and wait for the original instance to reconnect. The node may still not be ready during this period, and retaining the original instance is no longer guaranteed after the window expires.\nProtection also needs to follow the user access path. Preserving Orchestrator alone does not necessarily preserve an existing connection. If client-proxy is replaced, the sandbox can remain alive while the connection breaks. We therefore included session-proxy and client-proxy in the validation.\nIn one test with a 50-second disconnect window, Nomad Clients did briefly enter disconnected. The observed unknown intervals for their original allocations were approximately 1.7-31.6 seconds, followed by recovery within the window:\nValidation item Observation Orchestrator, session-proxy, and client-proxy Original allocations preserved; no additional task restarts Original sandbox process identities, memory, and files 10 / 10 preserved; final independent checks completed Original HTTP NDJSON streams 23 / 23 preserved Short requests during the formal observation period 12,581 requests, 0 errors With disconnect configured, the Clients briefly lost control-plane contact, but their original tasks remained in place until reconnection, without being replaced.\nBeyond Task Preservation: How Node Status Affects Sandbox Creation Capacity disconnect preserves original tasks; it does not prevent a Client from being declared disconnected after its heartbeat expires. In other words, Orchestrator and existing sandboxes can remain running without the node remaining eligible to receive new sandbox placements.\nIn this E2B implementation, the API normally synchronizes node information from Nomad every 20 seconds, selecting nodes in the sandbox node pool whose status is ready. The core filter is:\n1 2 3 options := \u0026amp;nomadapi.QueryOptions{ Filter: `Status == \u0026#34;ready\u0026#34; and NodePool == \u0026#34;default\u0026#34;`, } If the query succeeds but a previously known node no longer appears in the results, the API marks it unhealthy, affecting subsequent placement.\nThe public E2B runtime also has an implementation that discovers Orchestrators through allocations. Its discovery filter requires ClientStatus == \u0026quot;running\u0026quot;. Its API synchronization logic also removes an original instance from the local node pool when that instance no longer appears in valid discovery results.\nThe two implementations filter different objects, but they highlight the same issue: placement decisions depend on Nomad\u0026rsquo;s state, not only on whether the original Orchestrator process is alive.\nUnder a high sandbox creation rate, some healthy hosts may continue running existing sandboxes while temporarily being unable to share the load of new requests. Creation pressure shifts to the remaining eligible nodes. If they lack sufficient capacity, creation can fail, queue, or time out.\nThis is fundamentally a blast-radius problem. The failure originates in a single server and directly disrupts communication for some Clients. Node state then affects API placement, transferring pressure to other healthy nodes. disconnect contains the \u0026ldquo;destroy original tasks\u0026rdquo; path, but it does not automatically contain the \u0026ldquo;exclude healthy capacity\u0026rdquo; and \u0026ldquo;overload the remaining nodes\u0026rdquo; paths.\nSolution 2: Reduce False Node Failure Detections with heartbeat_grace disconnect addresses the situation after a node has been declared disconnected: do not abandon its original tasks immediately. Since node state also affects creation capacity, we need to look one step earlier. Can we give the Client enough time to switch paths before declaring it disconnected?\nThis is where the Server-side heartbeat_grace setting applies:\n1 2 3 server { heartbeat_grace = \u0026#34;50s\u0026#34; } It adds time beyond the dynamic TTL. Changing the default grace from 10 to 50 seconds adds 40 seconds of headroom. Combined with the normal TTL of approximately 10-20 seconds, the reference budget becomes roughly 60-70 seconds from the last successful heartbeat.\nheartbeat_grace Sequence: Allow More Switching Time Before Declaring a Node Disconnected Unlike disconnect, this changes how long the Leader waits for the next successful heartbeat. The example still assumes that the same Leader remains healthy throughout:\nsequenceDiagram accTitle: How heartbeat_grace provides switching time before node failure detection accDescr: t=0 is the last successful heartbeat. With an illustrative TTL of 15 seconds and grace of 50 seconds, expiration is at 65 seconds. A heartbeat restored at 40 seconds prevents this disconnection. If no heartbeat succeeds by 65 seconds, failure handling begins. These are illustrative, not measured, timestamps. autonumber participant Time as Relative timeline participant C as Nomad Client participant F as Original Follower participant L as Leader participant T as Original task Note over C,T: Illustrative: TTL=15s, grace=50st=0: last successful heartbeat at LeaderNot measured or to scale, scheduling delay omitted Note over Time: 0sLast successful heartbeat C-\u003e\u003eF: Node.UpdateStatus F-\u003e\u003eL: t=0: Forward heartbeat and renew timer L-\u003e\u003eL: Set expiration to t=65s (15+50) L--\u003e\u003eF: Return dynamic TTL=15s F--\u003e\u003eC: Schedule next heartbeat using the dynamic TTL Note over Time: 5s Note over F: t=5s: Assume the server fails Note over Time: About 15s C-xF: t~15s: Next heartbeat RPC does not return promptly Note over C: Wait for failure detection and switch to a healthy server Note over Time: About 25sExpiration with default grace Note over L: t~25s: Default grace would have expiredThe extended budget still runs until t=65s alt Assume heartbeat recovers at t=40s, before t=65s Note over Time: 40sBefore the 65s expiration point C-\u003e\u003eL: Complete heartbeat through a healthy server L-\u003e\u003eL: Reset the TTL + grace timer Note over L,T: No node disconnection or task replacement triggered by this heartbeat failure else Still no heartbeat at t=65s, or the Client has actually failed Note over Time: About 65s15s TTL + 50s grace Note over L: t~65s (15+50): Heartbeat budget expires L-\u003e\u003eL: t~65s+: Declare node failure and begin subsequent task handling endAcross two complete server-stop tests with grace set to 50 seconds and no disconnect policy on the key tasks, none of the 20 surviving Clients in either run was observed entering down or disconnected, and no original tasks were replaced. This matched the expected behavior: if switching completes before the budget expires, there is no need to enter the subsequent disconnection and task-handling paths.\nheartbeat_grace gives the Leader more time to wait. If connectivity recovers in time, that heartbeat failure does not lead to a node-disconnection decision.\nHowever, the cost becomes clearer when a Client actually fails. When a Server fails but the Client is healthy, we want to wait a little longer. When the Client\u0026rsquo;s host really has failed, we want to detect it quickly and stop placing work there. The same heartbeat signal cannot guarantee both \u0026ldquo;never falsely mark a healthy node down\u0026rdquo; and \u0026ldquo;immediately detect a real failure.\u0026rdquo; A longer grace delays real Client-failure detection at the Nomad heartbeat layer, although application health checks may exclude the failed node earlier.\nFrom a blast-radius perspective, the two adjustments place the cost at different points:\nAdjustment Benefit Cost and boundary Moderately increase heartbeat_grace Give the Leader more time for the next heartbeat, reduce false failure detections on healthy Clients, and lower the risk of unnecessary task replacement or exclusion from the creation pool Real Client failures also become visible later at the Nomad heartbeat layer Shorter grace + targeted disconnect Expose disconnection sooner after a real Client failure while giving original tasks a short reconnection window During a Server failure, some healthy Clients may still temporarily leave the creation pool, shifting pressure to the remaining nodes Summary: Turning Heartbeat Findings into Sandbox Resilience This investigation started with a simple question: why were tasks on healthy hosts rebuilt when only one Server was lost? Following the logs and code revealed a chain of architectural decisions that affect workloads: whether a heartbeat arrives in time, whether the node is declared disconnected, whether the original tasks are retained, and whether the layer above still treats the node as available capacity.\nFor E2B, we need to protect three goals separately:\nExisting sandbox runtime state: Separate node disconnection from immediately abandoning original tasks, leaving room to recover from brief control-plane failures. Existing user connections: Cover Orchestrator, session-proxy, and client-proxy rather than only verifying that the sandbox still exists. Creation capacity and real-failure recovery: Observe both the erroneous exclusion of healthy nodes and delays in detecting failed nodes or replacing tasks, while maintaining headroom on the remaining capacity. Ultimately, resilience does not mean every failure causes zero interruption. It means preserving valuable runtime state during short disconnections, keeping recovery bounded when a real failure occurs, and limiting the knock-on effects to a level the workload can tolerate.\nReferences Nomad Server Configuration: heartbeat_grace Nomad Client Heartbeats Nomad disconnect Specification Nomad Client Heartbeat Scheduling Nomad Leader Heartbeat Timers and Expiration Nomad Allocation Disconnect Expiration E2B Runtime: Nomad Discovery Filters E2B Runtime: API Node Synchronization hashicorp/nomad#17974: Non-Leader Connectivity Problems and Allocation Restarts ","date":"2026-10-22T00:00:00+08:00","image":"/p/e2b-sandbox-resilience-nomad-heartbeats/images/cover.png","permalink":"/p/e2b-sandbox-resilience-nomad-heartbeats/","title":"Building E2B Sandbox Resilience: Lessons from Nomad's Heartbeat Mechanism"},{"content":"In the previous article Building Resilient Azure AI Architecture with API Management Gateway, we built a resilient gateway architecture for multiple Microsoft Foundry resources using Azure API Management — Backend Load Balancing Pool for load distribution, and a retry policy that automatically switches to healthy instances when backends return 4xx/5xx errors. This mechanism makes backend failures nearly invisible to clients.\nBut \u0026ldquo;invisible\u0026rdquo; is precisely the challenge for operations teams: The Retry mechanism, while protecting clients, also hides the details of intermediate failures. When a request goes through 3 retries and ultimately returns 200, operations staff have no way of knowing why the first two attempts failed — was it a 429 rate limit? A 404 deployment not found? Or a 500 server error? Which backend had the issue? What did the error body say?\nThis article builds on the previous architecture to achieve complete Retry observability through Application Insights Diagnostic Logs, without modifying any Policy code, helping developers and operations teams:\n📋 Record detailed information for each Retry failure — including the failed backend address, HTTP status code, error response body, and APIM request ID 🔍 Reconstruct complete Retry chains via KQL queries — using operation_Id to correlate all retry records for the same request 🔔 Configure automated alerts — notify the operations team via email when Retry failure counts exceed thresholds 1. Architecture Overview This article adds an Application Insights observability layer on top of the APIM + Foundry resilient architecture from the previous article. No changes to existing APIM Policies or Backend configurations are needed — Retry monitoring and alerting are achieved entirely through Diagnostic Logs configuration.\nComponents from the previous article (unchanged):\nComponent Role Azure API Management Unified gateway, executing routing, Retry, and load balancing policies Backend Load Balancing Pool Pool of multiple Foundry resources, distributing requests via Round-Robin New components in this article:\nComponent Role Application Insights Receives APIM native telemetry (requests / dependencies), recording details of each Retry backend call Log Alert Automatically triggers alert notifications based on KQL queries when failure counts exceed thresholds Action Group Defines alert actions (Email/SMS/Webhook) Core design principles:\nZero code changes — No Policy modifications needed, fully implemented through APIM Diagnostic Logs configuration Native Telemetry — APIM\u0026rsquo;s dependencies table automatically records each forward-request call (including intermediate Retry failures), combined with Backend Response Headers to log and Body bytes configuration to capture error details and Foundry request IDs Full Retry chain visibility — All Retry attempts for the same request share the same operation_Id, making it easy to reconstruct the complete retry chain in KQL Proactive alerting — Log Alert rules automatically detect failure trends and promptly notify the operations team The following steps will guide you through building the complete Retry observability solution:\nSection Action Goal 2 Create Application Insights Set up log storage and query infrastructure 3 Bind APIM Logger Associate APIM with App Insights 4 Configure API Diagnostic Logs Enable App Insights logging for the target API, configure Verbosity, Backend Response Headers and Body 5 Verify Data Confirm Retry records in the dependencies table in App Insights 6 Configure Alert Rules Create Log Alert + Action Group for automated email notifications 2. Create an Application Insights Instance Create a workspace-based Application Insights instance in the same subscription and region as APIM to receive APIM telemetry data.\n2-1) In the Azure Portal search bar, type Application Insights and select the Application Insights service\n2-2) Click + Create, fill in the following key configurations and complete creation\nConfiguration Recommended Value Description Subscription Same as APIM Keep in the same subscription for easier management Resource group apim-ai-hub Same resource group as APIM Name ai-hub-app-insight Specify an Application Insights instance name Region Japan East Same region as APIM to reduce data transmission latency Workspace Default System automatically creates a Log Analytics workspace, or select one you\u0026rsquo;ve created 📝 Note:\nApplication Insights is workspace-based, with underlying data stored in a Log Analytics workspace. A workspace is automatically associated during creation — no manual creation needed.\n3. Bind APIM Logger Associate the Application Insights instance created in the previous step with APIM, enabling APIM to send telemetry data to App Insights.\n3-1) Navigate to the APIM instance → Left menu Monitoring → Application Insights → Click + Add\nConfiguration Recommended Value Description Application Insights instance ai-hub-app-insight Select the Application Insights instance just created ☐ Use as default and enable basic logging for all APIs Unchecked When checked, this Logger becomes the global default, enabling basic logging for all APIs. Can reduce throughput by 40-50% under high traffic (\u0026gt;1000 req/s). Recommended to enable per-API in Step 4 ☐ Add availability monitor Unchecked When checked, App Insights periodically validates whether the APIM gateway endpoint is responding, with results displayed in App Insights\u0026rsquo; Availability panel. Not needed for this scenario 4. Configure API Diagnostic Logs Enable Application Insights logging for the target AI API, configuring sampling rate, error recording, Backend Response, and other parameters.\n4-1) Navigate to APIM → APIs → Select target API → Switch to Settings tab → Scroll down to Diagnostic Logs area, click Enable\n4-2) Select the Application Insights tab, check Enable, and configure with the following parameters\nConfiguration Recommended Value Description Destination ai-hub-app-insight Select the bound App Insights instance. ⚠️ If it shows \u0026ldquo;No App Insights were configured\u0026rdquo;, go back to Step 3 to bind the Logger first Sampling (%) 100 Sampling rate, 100 for full recording (can be adjusted to 25-50 for production) Always log errors ✅ Enable Ensures error requests are not filtered by sampling — all 4xx/5xx are recorded even when Sampling \u0026lt; 100% Log client IP address ✅ Enable Records caller IP, useful for troubleshooting Support custom metrics Unchecked Only needed when using the emit-metric policy, not used in this article Verbosity ⚠️ Information Controls the logging level for native telemetry, recommended to select Information or Verbose (see explanation below) Correlation protocol W3C Modern standard, supports cross-service distributed tracing using traceparent header to correlate frontend and backend requests Verbosity Configuration Notes:\n❗ Important:\nVerbosity should be set to Information or Verbose, not Error.\nVerbosity controls the logging level for the entire request chain — successful final requests (200) are treated as information level, failed requests (4xx/5xx) are treated as error level.\nVerbosity Final Request Successful (200) Final Request Failed (4xx/5xx) Information ✅ ✅ requests recorded + ✅ All dependencies recorded (including intermediate Retry failures) ✅ requests recorded + ✅ All dependencies recorded Error ❌ ❌ Nothing recorded (both request and dependencies are lost) ✅ requests recorded + ✅ Associated dependencies recorded ⚠️ Warning:\nWhen Verbosity=Error: If 2 out of 3 Retry attempts fail (404) but the 3rd attempt succeeds (200), the entire request chain will not appear in any table — including those 2 intermediate failed dependency records. This creates a blind spot for Retry observability.\nSelecting Information ensures that regardless of whether the final result is success or failure, all Retry processes are fully recorded.\nAdditional settings — Backend Response Configuration:\nThis is the key configuration for achieving Retry observability. Check Backend Response, configure Headers to log and Body bytes — APIM will include this information in the Properties field of the dependencies table.\nConfiguration Recommended Value Description Headers to log apim-request-id Records the request tracking ID returned by Foundry, used for locating backend requests when submitting support tickets to Microsoft Body bytes to log 1024 Records the first 1KB of response body, capturing error JSON details (e.g., DeploymentNotFound, Too Many Requests, etc.) 📝 Note:\nHeaders to log and Body bytes apply to all sampled requests (including successful ones), without distinguishing between success and failure. This data appears in two App Insights tables:\nrequests table — Records the final request returned to the client (frontend perspective) dependencies table — Records each forward-request call (backend perspective, including each intermediate Retry attempt) The dependencies table is the core data source for Retry observability.\nClick Save to complete the configuration.\n⚠️ Warning:\nConfiguration changes take several minutes to propagate to APIM gateway instances. If you test immediately and see no data, please wait 5 minutes before checking.\n5. Verify Data After configuration is complete, send a few test requests that will trigger Retry (e.g., call a non-existent model deployment), wait approximately 5 minutes, then verify data in Application Insights.\n5-1) Navigate to Application Insights → Monitoring → ① Logs, ② Switch to Tables view, ③ Find the dependencies table under the Application Insights category and click Run\nThe dependencies table generates an independent record for each forward-request call within the retry block — including intermediate failed Retry attempts and the final successful request. In the results on the right, you can see multiple records pointing to different backends (e.g., ai-hub-swedencentral-02, ai-hub-eastus2-01, etc.), all belonging to the same request\u0026rsquo;s Retry chain.\n5-2) Expand a single record to view detailed fields and customDimensions\nAfter expanding, you can see the complete information of the dependency record, with key troubleshooting fields highlighted:\nField Description target Full address of the requested backend resultCode HTTP status code duration Call duration success Whether successful Response-Body Success/error response JSON details Response-apim-request-id Foundry-side request ID (different for each Retry), useful for submitting troubleshooting tickets 💡 Tip:\nUse operation_Id to link all Retry records for the same request together, reconstructing the complete retry chain. Response-apim-request-id can be used to locate specific backend requests when submitting support tickets to Microsoft.\n6. Configure Alert Rules Automatically notify the operations team via email when Retry failure counts exceed thresholds. Alert rules are created on Application Insights (not APIM).\n6-1) Write and verify KQL query on the Logs page\nNavigate to Application Insights → Monitoring → Logs, ① create a new query tab, ② switch to KQL mode, ③ enter the following query and ④ click Run to verify results:\n1 2 3 4 dependencies | where success == false | where resultCode in (\u0026#34;429\u0026#34;, \u0026#34;500\u0026#34;, \u0026#34;502\u0026#34;, \u0026#34;503\u0026#34;, \u0026#34;504\u0026#34;) or toint(resultCode) \u0026gt;= 400 | summarize FailureCount = count() Adjust the status code filter as needed:\nScenario Filter Condition All failures where success == false Rate limiting only (429) where resultCode == \u0026quot;429\u0026quot; 5xx server errors only where toint(resultCode) \u0026gt;= 500 429 + 5xx where resultCode == \u0026quot;429\u0026quot; or toint(resultCode) \u0026gt;= 500 Exclude 404 where success == false and resultCode != \u0026quot;404\u0026quot; Confirm the query returns the expected FailureCount value.\n6-2) Click the ... menu in the top right → + New alert rule\nThe system will automatically carry over the current KQL query into the Alert rule\u0026rsquo;s Condition configuration.\n6-3) Confirm query and Measurement configuration on the Condition tab\nThree key configurations highlighted in the screenshot:\nAnnotation Configuration Value Description ① Search query KQL from previous step (auto-populated) Contains success == false + status code filter + summarize FailureCount = count() ② Measure FailureCount ⚠️ Must select FailureCount (auto-detected from KQL\u0026rsquo;s summarize). If it defaults to Table rows, switch manually ③ Aggregation granularity 3 hours Aggregation granularity — aggregates FailureCount within this time range into a single data point for evaluation Other settings keep defaults:\nQuery type: Aggregated logs Aggregation type: Total (sum of FailureCount) 6-4) Scroll down to configure Alert logic\nConfiguration Value Description Threshold type Static Use fixed threshold Operator Greater than Trigger when FailureCount exceeds threshold Threshold value 10 Adjust based on business tolerance Frequency of evaluation 15 minutes Evaluate every 15 minutes 📝 Note:\n📊 The Preview chart below displays the FailureCount trend and threshold line (dashed), helping you assess whether the threshold setting is reasonable. Areas where the blue solid line exceeds the dashed threshold line indicate periods that would trigger alerts.\n💰 Estimated monthly cost is approximately $0.50 USD (depends on evaluation frequency).\nClick Next: Actions \u0026gt; to proceed.\n6-5) Configure alert actions on the Actions tab\nIf the Portal displays the Use quick actions (preview) option (new UI), you can complete Action Group creation directly on this page without creating one separately:\nAnnotation Configuration Description ① Use quick actions (preview) Select this option, and the Portal will automatically create an Action Group ② Quick actions panel Fill in Action group name, Display name, check Email and enter email address → Save ③ Email subject Custom alert email subject, e.g., AI Hub Retry Alert 📝 Note:\nIf the Portal doesn\u0026rsquo;t show the quick actions option (legacy UI), select Use action groups → + Create action group, and follow steps 6-6 ~ 6-8 below to create one manually.\n6-6) Fill in Action Group basic information\nConfiguration Value Description Region Global Recommended to select Global for Action Groups Action group name ai-hub-retry-alert-action Unique identifier Display name AI-Hub-Retry Limited to 12 characters, displayed in notifications 6-7) Switch to the Notifications tab and configure email notifications\nConfiguration Value Description Notification type Email/SMS message/Push/Voice Select notification method Name Recipient name Notification recipient identifier Email ✅ Check and enter email Alert email recipient address 📝 Note:\nThe Actions tab allows configuration of richer automated actions (Automation Runbook, Azure Function, Logic App, Webhook, etc.). These are not used in this article — simply skip.\n6-8) Switch to the Review + create tab, confirm configuration and click Create\nAfter creation, you\u0026rsquo;ll receive an Azure confirmation email indicating you\u0026rsquo;ve been added to the Action Group:\n6-9) Return to the Alert rule\u0026rsquo;s Actions page, confirm the Action Group is associated, and fill in the email subject\nEnter a custom alert email subject in the Email subject field, e.g., AI Hub Retry Alert.\n6-10) Switch to the Details tab and fill in Alert rule basic information\nConfiguration Value Description Severity 2 - Warning Alert severity level Alert rule name AI-Hub-Alert Alert rule name Region Japan East Same region as App Insights Identity Default Use default identity 6-11) Switch to Review + create to confirm all configurations, click Create to complete\n6-12) Verify alert email\nApproximately 15 minutes after creation, when FailureCount exceeds the threshold (10), you\u0026rsquo;ll receive an alert email:\nThe email contains key information:\nField Value Description Alert name AI-Hub-Alert Name of the triggered alert rule Severity Warning Alert level Metric value 15 Actual FailureCount Threshold 10 Configured threshold Fired time Specific time (UTC) When the alert was triggered Click View alert details in the email to jump directly to Azure Portal for details; View search results to view the KQL query results that triggered the alert.\n6-13) (Optional) Fine-tune alert parameters\nAfter the alert rule is created, navigate to Application Insights → Monitoring → Alerts → Alert rules → Select the corresponding rule → Click the Edit button:\nIn the editing page\u0026rsquo;s Details tab → Advanced options, fine-tune further:\nConfiguration Description Recommended Value Mute actions Enter a silent period after triggering, during which no repeat notifications are sent ✅ Check Mute actions for Silent duration — no notifications during this period even if conditions persist 3 hours (adjust as needed) Automatically resolve alerts Automatically change alert status from Fired to Resolved when conditions are no longer met Check as needed 💡 Tip:\nIf the evaluation frequency is 15 minutes and Mute is not configured, an email notification will be sent every 15 minutes while alert conditions persist. Configuring Mute prevents repeated notifications after the first alert trigger, avoiding email flooding.\nAdditionally, you can adjust Aggregation granularity, Threshold value, Frequency of evaluation, and other parameters on the editing page to optimize alert sensitivity.\n7. Appendix: Advanced KQL Queries and Client IP Configuration (Optional) 7-1) Enable Real Client IP Recording Application Insights does not store client IP addresses by default (privacy protection), and the client_IP field displays as 0.0.0.0. Disable IP masking via CLI to record real IPs:\n1 2 3 4 5 az resource update \\ --resource-group \u0026lt;resource-group\u0026gt; \\ --name \u0026lt;app-insights-name\u0026gt; \\ --resource-type \u0026#34;Microsoft.Insights/components\u0026#34; \\ --set properties.DisableIpMasking=true ⚠️ Warning:\nDisabling IP masking will record real client IP addresses. Please ensure this complies with your organization\u0026rsquo;s privacy requirements.\n📖 Reference: Geolocation and IP address handling: https://learn.microsoft.com/azure/azure-monitor/app/ip-collection\n7-2) Correlate Client IP with Retry Failure Records The dependencies table itself does not contain client IP (it records APIM → backend outbound calls). You need to JOIN with the requests table via operation_Id:\n1 2 3 4 5 6 7 8 9 10 11 12 13 dependencies | where timestamp \u0026gt; ago(1h) | where success == false | join kind=leftouter ( requests | project operation_Id, req_client_IP = client_IP ) on operation_Id | project timestamp, target, resultCode, ClientIP = req_client_IP, ErrorBody = tostring(customDimensions[\u0026#34;Response-Body\u0026#34;]), APIMRequestId = tostring(customDimensions[\u0026#34;Response-apim-request-id\u0026#34;]), operation_Id | order by timestamp desc 📝 Note:\nBoth requests and dependencies tables have a client_IP field, but with different meanings:\nrequests.client_IP — IP of the client calling APIM (real client) dependencies.client_IP — APIM gateway\u0026rsquo;s outbound IP (not the client) When JOINing, use renaming (e.g., req_client_IP) to avoid field conflicts.\n7-3) More Useful KQL Queries Reconstruct complete Retry chain by operation_Id (including the successful attempt):\n1 2 3 4 5 6 7 8 9 dependencies | where timestamp \u0026gt; ago(1h) | summarize CallCount = count(), Backends = make_list(target), StatusCodes = make_list(resultCode), Durations = make_list(duration) by operation_Id | where CallCount \u0026gt; 1 | order by CallCount desc Failure trend chart:\n1 2 3 4 5 dependencies | where timestamp \u0026gt; ago(24h) | where success == false | summarize FailureCount = count() by bin(timestamp, 5m), target | render timechart For alerting (grouped by backend + status code):\n1 2 3 4 5 dependencies | where timestamp \u0026gt; ago(2h) | where success == false | summarize FailureCount = count() by target, resultCode | where FailureCount \u0026gt; 0 Summary Through this article\u0026rsquo;s implementation, we\u0026rsquo;ve built a complete Retry observability solution on top of the resilient gateway architecture from the previous article:\nCapability Implementation Each Retry failure recorded APIM native dependencies table automatically records each forward-request call Error Body recording Backend Response Body bytes=1024, error JSON details appear in Properties Request tracking IDs operation_Id (unchanged across Retries) + Response-apim-request-id (Foundry-side ID) Call duration Native DurationMs field, precise to milliseconds KQL queries Support aggregation analysis by backend, status code, and time dimensions Automated alerting Log Alert rules + Action Group email notifications For users who have already deployed the resilient architecture from the previous article, this article requires no Policy code changes — complete Retry observability is achieved solely through APIM Diagnostic Logs configuration (binding App Insights + setting Verbosity to Information + enabling Backend Response Headers/Body).\nThose errors hidden by the Retry mechanism are now clearly recorded in Application Insights\u0026rsquo; dependencies table, ready for operations staff to review and address.\nReferences Document Link How to integrate Azure API Management with Azure Application Insights https://learn.microsoft.com/azure/api-management/api-management-howto-app-insights Diagnostic - Create Or Update REST API https://learn.microsoft.com/rest/api/apimanagement/diagnostic/create-or-update Application Insights telemetry data model https://learn.microsoft.com/azure/azure-monitor/app/data-model-complete Geolocation and IP address handling (IP masking) https://learn.microsoft.com/azure/azure-monitor/app/ip-collection Subscriptions in Azure API Management https://learn.microsoft.com/azure/api-management/api-management-subscriptions Tutorial: Create a log search alert for an Azure resource https://learn.microsoft.com/azure/azure-monitor/alerts/tutorial-log-alert Create and manage action groups https://learn.microsoft.com/azure/azure-monitor/alerts/action-groups Kusto Query Language (KQL) overview https://learn.microsoft.com/azure/data-explorer/kusto/query/ Performance implications and log sampling https://learn.microsoft.com/azure/api-management/api-management-howto-app-insights#performance-implications-and-log-sampling Azure Monitor pricing https://azure.microsoft.com/pricing/details/monitor/ ","date":"2026-04-29T00:00:00+08:00","image":"/p/azure-apim-ai-resilience-part2/images/cover.png","permalink":"/p/azure-apim-ai-resilience-part2/","title":"Building Resilient Azure AI Architecture with API Management Gateway (Part 2) — Retry Observability and Alerting"},{"content":"As enterprise demand for AI capabilities grows, organizations are deeply integrating Microsoft Foundry model services into core business systems. As AI moves from experimentation to production, high availability, elastic scaling, unified governance, and security controls become unavoidable themes.\nIn production, a single subscription instance fails to meet requirements for continuity, stability, and throughput. A mature architecture consolidates resources across subscriptions, aggregating AI quotas to maximize throughput, with traffic distribution, automatic failover, and unified access control.\nAzure API Management (APIM), as Azure\u0026rsquo;s native API gateway, is naturally suited for this role. By deploying APIM as the unified entry point, combined with the following capabilities, we can build an enterprise-grade, highly resilient AI architecture:\n🔀 Backend Load Balancing Pool — Load balancing and failover across subscriptions and Foundry instances, aggregating distributed quotas 🔐 Managed Identity — Zero-key secure authentication between APIM and backend AI services 🛡️ Unified API Governance — Request routing, traffic control, log auditing, and policy management at the gateway layer This article walks through a complete hands-on example: from resource deployment and identity configuration to load balancing policies, building a production-ready resilient gateway architecture targeting multiple Microsoft Foundry resources.\nArchitecture Overview This architecture uses a centralized API gateway + multi-subscription backend pattern, with APIM as the unified entry point, distributing requests round-robin to Foundry instances across multiple subscriptions and regions.\nCore design principles:\nUnified Entry Point — Clients only need the APIM endpoint; the pool uses Round-Robin by default Simplified Security Authentication — Zero-key communication via Managed Identity; clients only need a single API Key Cross-Subscription Quota Aggregation — Aggregate quotas across subscriptions into a unified capacity pool Cross-Region Disaster Recovery — APIM automatically routes to healthy instances when a region becomes unavailable APIM\u0026rsquo;s Policy engine also provides flexible traffic control:\nPinned Routing — via X-AI-Foundry-Target header Auto Failover — Auto-retry with exponential backoff on 4xx/5xx Request Tracing — X-AI-Foundry-Backend response header for tracing Architecture setup steps:\nSection Action Goal Platform 1 Create APIM instance Set up the unified gateway entry point and enable Managed Identity Azure Portal 2 Create Foundry resources Build the backend resource pool across multiple subscriptions and regions Azure Portal 3 Deploy AI models Enable AI service capability on backend resources (using Sora2 as an example) Foundry Portal 4 Configure RBAC Grant APIM Managed Identity permission to access backends Azure Portal 5 Configure Backend + LB Pool Register backends and create the load balancing pool Azure Portal (APIM) 6 Create API + Policy Define the API entry point and configure routing and failover Azure Portal (APIM) 7 Test and validate Verify load balancing and pinned backend routing curl / Postman Create APIM Instance Create an API Management instance in Azure Portal, selecting v2 Tier, and enable System Assigned Managed Identity during creation.\nPortal Steps: Search API Management Service → + Create → Fill in configuration → Enable on the Managed identity tab → Review + install\nCLI Alternative:\n1 2 3 4 5 6 7 8 9 10 11 az rest --method PUT \\ --url \u0026#34;https://management.azure.com/subscriptions/\u0026lt;subscription-id\u0026gt;/resourceGroups/\u0026lt;resource-group\u0026gt;/providers/Microsoft.ApiManagement/service/\u0026lt;apim-name\u0026gt;?api-version=2024-05-01\u0026#34; \\ --body \u0026#39;{ \u0026#34;location\u0026#34;: \u0026#34;\u0026lt;region\u0026gt;\u0026#34;, \u0026#34;sku\u0026#34;: { \u0026#34;name\u0026#34;: \u0026#34;\u0026lt;BasicV2|StandardV2|PremiumV2\u0026gt;\u0026#34;, \u0026#34;capacity\u0026#34;: 1 }, \u0026#34;identity\u0026#34;: { \u0026#34;type\u0026#34;: \u0026#34;SystemAssigned\u0026#34; }, \u0026#34;properties\u0026#34;: { \u0026#34;publisherName\u0026#34;: \u0026#34;\u0026lt;organization-name\u0026gt;\u0026#34;, \u0026#34;publisherEmail\u0026#34;: \u0026#34;\u0026lt;admin-email\u0026gt;\u0026#34; } }\u0026#39; After Creation:\nStatus: Online Record Gateway URL (for example: https://\u0026lt;apim-name\u0026gt;.azure-api.net) Record the Managed Identity Object (principal) ID for RBAC Create Foundry Resources Create Foundry resources across multiple subscriptions and regions, each with a corresponding project.\nPortal Steps: Search Microsoft Foundry → Create a resource → Fill in Subscription / Region / Name / Project name → Create\nCLI Alternative:\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 az cognitiveservices account create \\ --subscription \u0026lt;subscription-id\u0026gt; \\ --resource-group \u0026lt;resource-group\u0026gt; \\ --name \u0026lt;foundry-resource-name\u0026gt; \\ --location \u0026lt;region-code\u0026gt; \\ --kind AIServices --sku S0 \\ --custom-domain \u0026lt;foundry-resource-name\u0026gt; \\ --allow-project-management \u0026amp;\u0026amp; \\ az cognitiveservices account project create \\ --subscription \u0026lt;subscription-id\u0026gt; \\ --name \u0026lt;foundry-resource-name\u0026gt; \\ --resource-group \u0026lt;resource-group\u0026gt; \\ --project-name \u0026lt;project-name\u0026gt; \\ --location \u0026lt;region-code\u0026gt; Example Resource Distribution:\nSubscription Region Resource Name Subscription A East US 2 foundry-eastus2-01 Subscription A Sweden Central foundry-swedencentral-01 Subscription B East US 2 foundry-eastus2-02 Subscription B Sweden Central foundry-swedencentral-02 Deploy Models Deploy AI models in each Foundry resource via the Foundry Portal.\nPortal Steps: In Foundry Portal, select the target project → Build → Models → Deploy a base model → Search for a model (for example sora-2) → Deploy → Default settings\nCLI Alternative:\n1 2 3 4 5 6 7 8 9 10 az cognitiveservices account deployment create \\ --subscription \u0026lt;subscription-id\u0026gt; \\ --resource-group \u0026lt;resource-group\u0026gt; \\ --name \u0026lt;foundry-resource-name\u0026gt; \\ --deployment-name \u0026lt;deployment-name\u0026gt; \\ --model-name \u0026lt;model-name\u0026gt; \\ --model-version \u0026lt;model-version\u0026gt; \\ --model-format \u0026lt;model-format\u0026gt; \\ --sku-name \u0026lt;sku-name\u0026gt; \\ --sku-capacity \u0026lt;capacity\u0026gt; Model names, versions, and SKUs vary by region. See: Models and Region Availability\nConfigure RBAC Grant the Cognitive Services OpenAI User role to APIM\u0026rsquo;s Managed Identity on each Foundry resource.\nPortal Steps: Go to the Foundry resource → Access control (IAM) → + Add → Add role assignment → Search Cognitive Services OpenAI User → In Members choose Managed identity → Select the API Management service → Review + assign\nCLI Alternative:\n1 2 3 4 5 6 7 8 9 10 11 12 # Get APIM Managed Identity Principal ID az apim show \\ --subscription \u0026lt;subscription-id\u0026gt; \\ --name \u0026lt;apim-name\u0026gt; \\ --resource-group \u0026lt;resource-group\u0026gt; \\ --query \u0026#34;identity.principalId\u0026#34; -o tsv # Assign role for each Foundry resource az role assignment create \\ --assignee \u0026lt;principal-id\u0026gt; \\ --role \u0026#34;Cognitive Services OpenAI User\u0026#34; \\ --scope /subscriptions/\u0026lt;subscription-id\u0026gt;/resourceGroups/\u0026lt;resource-group\u0026gt;/providers/Microsoft.CognitiveServices/accounts/\u0026lt;foundry-resource-name\u0026gt; Cognitive Services OpenAI User is the minimum permission role—allows inference calls but not resource configuration changes.\nConfigure Backend + LB Pool Create Backend Create a Backend for each Foundry resource with Managed Identity authentication.\nGet OpenAI Endpoint: On the project Home page in Foundry Portal, find Azure OpenAI endpoint, or use the CLI:\n1 2 3 4 5 az cognitiveservices account show \\ --subscription \u0026lt;subscription-id\u0026gt; \\ --resource-group \u0026lt;resource-group\u0026gt; \\ --name \u0026lt;foundry-resource-name\u0026gt; \\ --query \u0026#34;properties.endpoints.\\\u0026#34;OpenAI Language Model Instance API\\\u0026#34;\u0026#34; -o tsv Portal Steps: APIM → Backends → + Create new backend → Fill in Name / Runtime URL → Managed Identity tab → Client identity = System assigned → Resource ID = https://cognitiveservices.azure.com → Create\nKey Configuration:\nConfiguration Example Value Description Name \u0026lt;foundry-resource-name\u0026gt; Recommended to match the Foundry resource name Runtime URL https://\u0026lt;foundry-resource-name\u0026gt;.openai.azure.com/openai/v1 Foundry OpenAI endpoint (+ openai/v1) Client identity System assigned identity Use APIM system-assigned managed identity Resource ID https://cognitiveservices.azure.com Token audience, fixed value CLI Alternative:\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 az rest --method PUT \\ --url \u0026#34;https://management.azure.com/subscriptions/\u0026lt;subscription-id\u0026gt;/resourceGroups/\u0026lt;resource-group\u0026gt;/providers/Microsoft.ApiManagement/service/\u0026lt;apim-name\u0026gt;/backends/\u0026lt;backend-name\u0026gt;?api-version=2024-05-01\u0026#34; \\ --body \u0026#39;{ \u0026#34;properties\u0026#34;: { \u0026#34;url\u0026#34;: \u0026#34;https://\u0026lt;foundry-resource-name\u0026gt;.openai.azure.com/openai/v1\u0026#34;, \u0026#34;protocol\u0026#34;: \u0026#34;http\u0026#34;, \u0026#34;credentials\u0026#34;: { \u0026#34;managedIdentity\u0026#34;: { \u0026#34;clientId\u0026#34;: null, \u0026#34;resource\u0026#34;: \u0026#34;https://cognitiveservices.azure.com\u0026#34; } } } }\u0026#39; Create LB Pool Portal Steps: APIM → Backends → Load balancer tab → + Create new pool → Fill in Pool Name → Select all Backends → Send requests evenly (Round-robin) → Create\nPortal provides two options: Send requests evenly (Round-robin) or Customize weight and priority.\nCreate API + Policy Create API Portal Steps: APIM → APIs → + Add API → HTTP → Fill in Display name / API URL suffix (openai/v1) → Leave Web service URL empty → Create\nThen add Operations: create /* wildcard path for POST, GET, and DELETE.\nThis example uses wildcard /* to proxy all requests. For finer control, create operations for specific paths like /videos/* for Sora2.\nConfigure Policy Select All operations → click \u0026lt;/\u0026gt; in Inbound processing → paste the policy below, update the pool name → Save\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 \u0026lt;policies\u0026gt; \u0026lt;inbound\u0026gt; \u0026lt;base /\u0026gt; \u0026lt;!-- Read request header so callers can pin a backend --\u0026gt; \u0026lt;set-variable name=\u0026#34;target\u0026#34; value=\u0026#34;@(context.Request.Headers.GetValueOrDefault(\u0026#34;X-AI-Foundry-Target\u0026#34;, \u0026#34;\u0026#34;))\u0026#34; /\u0026gt; \u0026lt;!-- Backend load balancing pool name --\u0026gt; \u0026lt;set-variable name=\u0026#34;pool_name\u0026#34; value=\u0026#34;\u0026lt;your-ai-hub-pool-name\u0026gt;\u0026#34; /\u0026gt; \u0026lt;choose\u0026gt; \u0026lt;when condition=\u0026#34;@(context.Variables.GetValueOrDefault\u0026lt;string\u0026gt;(\u0026#34;target\u0026#34;) != \u0026#34;\u0026#34;)\u0026#34;\u0026gt; \u0026lt;set-backend-service backend-id=\u0026#34;@(context.Variables.GetValueOrDefault\u0026lt;string\u0026gt;(\u0026#34;target\u0026#34;))\u0026#34; /\u0026gt; \u0026lt;/when\u0026gt; \u0026lt;otherwise\u0026gt; \u0026lt;set-backend-service backend-id=\u0026#34;@((string)context.Variables[\u0026#34;pool_name\u0026#34;])\u0026#34; /\u0026gt; \u0026lt;/otherwise\u0026gt; \u0026lt;/choose\u0026gt; \u0026lt;/inbound\u0026gt; \u0026lt;outbound\u0026gt; \u0026lt;base /\u0026gt; \u0026lt;set-header name=\u0026#34;X-AI-Foundry-Backend\u0026#34; exists-action=\u0026#34;override\u0026#34;\u0026gt; \u0026lt;value\u0026gt;@(context.Request.Url.Host.Split(\u0026#39;.\u0026#39;)[0])\u0026lt;/value\u0026gt; \u0026lt;/set-header\u0026gt; \u0026lt;/outbound\u0026gt; \u0026lt;on-error\u0026gt; \u0026lt;base /\u0026gt; \u0026lt;/on-error\u0026gt; \u0026lt;backend\u0026gt; \u0026lt;choose\u0026gt; \u0026lt;when condition=\u0026#34;@(context.Variables.GetValueOrDefault\u0026lt;string\u0026gt;(\u0026#34;target\u0026#34;) != \u0026#34;\u0026#34;)\u0026#34;\u0026gt; \u0026lt;forward-request buffer-request-body=\u0026#34;true\u0026#34; /\u0026gt; \u0026lt;/when\u0026gt; \u0026lt;otherwise\u0026gt; \u0026lt;retry condition=\u0026#34;@(context.Response == null || context.Response.StatusCode \u0026gt;= 400)\u0026#34; count=\u0026#34;3\u0026#34; interval=\u0026#34;1\u0026#34; delta=\u0026#34;1\u0026#34; max-interval=\u0026#34;5\u0026#34; first-fast-retry=\u0026#34;true\u0026#34;\u0026gt; \u0026lt;set-backend-service backend-id=\u0026#34;@((string)context.Variables[\u0026#34;pool_name\u0026#34;] )\u0026#34; /\u0026gt; \u0026lt;forward-request buffer-request-body=\u0026#34;true\u0026#34; /\u0026gt; \u0026lt;/retry\u0026gt; \u0026lt;/otherwise\u0026gt; \u0026lt;/choose\u0026gt; \u0026lt;/backend\u0026gt; \u0026lt;/policies\u0026gt; Policy Logic:\nArea Function inbound Read X-AI-Foundry-Target; if present, route to the specified backend, otherwise use the LB Pool round-robin outbound Return the actual backend name in the X-AI-Foundry-Backend response header backend Forward directly for pinned routing; in pool mode, auto-retry and switch backend on failure (up to 3 attempts with exponential backoff) Test and Validate Prerequisites:\nGather the following before testing:\nGet Gateway URL: APIM → Overview → Gateway URL Get API Key: APIM → Subscriptions → Built-in all-access → Show keys → Primary key Test 1: Load Balancing Send consecutive requests without X-AI-Foundry-Target, and observe X-AI-Foundry-Backend rotating across backends:\n1 2 3 curl -D - -o /dev/null --location \\ \u0026#39;https://\u0026lt;apim-gateway-url\u0026gt;/openai/v1/videos\u0026#39; \\ --header \u0026#39;Ocp-Apim-Subscription-Key: \u0026lt;your-subscription-key\u0026gt;\u0026#39; Expected: X-AI-Foundry-Backend changes with each request, confirming Round-robin is working.\nTest 2: Pinned Backend Routing Use X-AI-Foundry-Target header to pin to a specific backend:\n1 2 3 4 5 6 7 curl -s -D - -o /dev/null --location \\ \u0026#39;https://\u0026lt;apim-gateway-url\u0026gt;/openai/v1/responses\u0026#39; \\ --header \u0026#39;Content-Type: application/json\u0026#39; \\ --header \u0026#39;Ocp-Apim-Subscription-Key: \u0026lt;your-subscription-key\u0026gt;\u0026#39; \\ --header \u0026#39;X-AI-Foundry-Target: \u0026lt;backend-name\u0026gt;\u0026#39; \\ --data \u0026#39;{\u0026#34;model\u0026#34;: \u0026#34;\u0026lt;model-name\u0026gt;\u0026#34;, \u0026#34;input\u0026#34;: \u0026#34;Hello\u0026#34;}\u0026#39; \\ | grep -i X-AI-Foundry-Backend Expected: X-AI-Foundry-Backend consistently returns the specified backend name.\nFAQ Q: Why not use APIM Backend\u0026rsquo;s Circuit Breaker?\nThis architecture targets load balancing and quota aggregation. Circuit Breaker would \u0026ldquo;break\u0026rdquo; on backend failure, but a 429 on one model shouldn\u0026rsquo;t block other models on the same backend. Simple failover via retry + set-backend-service is more appropriate.\nQ: Is this architecture only for Sora2?\nNo. It applies to any Foundry / Azure OpenAI model service (Responses API, Chat Completions, Embeddings, Image Generation, etc.)—just point the Backend URL to the corresponding endpoint.\nReference Documentation Microsoft Foundry Overview: https://learn.microsoft.com/azure/foundry/what-is-foundry Foundry RBAC: https://learn.microsoft.com/azure/foundry-classic/openai/how-to/role-based-access-control APIM v2 Tier: https://learn.microsoft.com/azure/api-management/v2-service-tiers-overview Backends \u0026amp; LB Pool: https://learn.microsoft.com/azure/api-management/backends Managed Identity: https://learn.microsoft.com/azure/api-management/api-management-howto-use-managed-service-identity Retry Policy: https://learn.microsoft.com/azure/api-management/retry-policy Video Generation / Sora2: https://learn.microsoft.com/azure/foundry/openai/concepts/video-generation Models \u0026amp; Regions: https://learn.microsoft.com/azure/foundry/foundry-models/concepts/models-sold-directly-by-azure Error Codes: https://learn.microsoft.com/azure/foundry/openai/supported-languages#error-handling ","date":"2026-04-03T00:00:00+08:00","image":"/p/azure-apim-ai-resilience/images/cover.png","permalink":"/p/azure-apim-ai-resilience/","title":"Building Resilient Azure AI Architecture with API Management Gateway"},{"content":"In today\u0026rsquo;s digital age, website security is paramount. SSL certificates, as a critical tool for protecting data transmission, have always been a key concern for developers and operations teams. In 2023, we released the China CloudFront SSL Plugin to facilitate the integration of free SSL certificates with CloudFront in the China region. We have continued to iterate on our solution. Now, we are pleased to announce the official release of the second generation of the China CloudFront SSL Plugin.\nMajor Upgrades China CloudFront SSL Plugin V2 introduces three core upgrades, making certificate management simpler, safer, and more efficient.\n1. Breaking Through the Single-Project Limitation with Unified Multi-Project Management In this new version, we have completely restructured the project management architecture:\nBefore (V1): Each stack could only manage a single project\u0026rsquo;s domain set. Managing multiple projects required deploying multiple stacks.\nAfter (V2): A single stack can now manage domain sets for multiple projects, significantly simplifying operations.\n2. A Brand-New Interactive Experience — No More Complex Operations To improve the user experience, we have completely redesigned the management interface:\nBefore (V1): An API management page built on Swagger UI that required manually constructing and sending API requests.\nAfter (V2): An intuitive graphical user interface where all operations can be completed with simple button clicks, greatly lowering the barrier to entry.\n3. Enhanced Security Mechanisms for Safer Operations Security has been comprehensively strengthened:\nBefore (V1): External APIs lacked effective security validation mechanisms.\nAfter (V2): An Access Key verification mechanism has been introduced — all API operations now require authentication, ensuring secure and controlled access.\nWhile introducing these new capabilities, we have preserved and reinforced the most popular features of the solution:\n✓ Cost Advantage\nFully serverless architecture with pay-per-invocation pricing Certificate renewal triggers every 30 days by default Only minimal storage and logging costs ✓ Operational Automation\nSeamless integration with CloudFront Automatic replacement of associated CloudFront certificates after renewal Scheduled automatic renewal via Amazon EventBridge ✓ Operational Transparency\nComprehensive email notification mechanism covering the entire certificate lifecycle Intuitive graphical dashboard for real-time certificate status monitoring Unified multi-project management and monitoring ✓ Open Source\nAll code is provided as open source Supports customization on top of the source code Easy to extend for enterprise-specific requirements These upgrades not only enhance the user experience but also provide more powerful support for China CloudFront certificate management. Whether managing certificates for a single website or multiple projects, V2 can handle it with ease.\nArchitecture As a certificate management solution for CloudFront in the China region, we designed a complete architecture based on serverless services, with automated deployment via Amazon CloudFormation templates.\n1. Core Components:\nLet\u0026rsquo;s Encrypt: A free, open, and automated certificate authority that provides free SSL certificate support for the solution Certbot: A free open-source tool for automated certificate acquisition, deployment, and renewal Amazon Lambda: The core compute component responsible for running the certificate issuance program, frontend interface, and certificate management API Amazon API Gateway: Provides a secure certificate management API interface — all operations require Access Key verification 2. Storage \u0026amp; Database:\nAmazon DynamoDB: A serverless database dedicated to storing project certificate issuance status and error information Amazon S3: Used for storing backup SSL certificates, supporting certificate download and backup management IAM SSL Certificate Storage: Dedicated storage for SSL certificates associated with CloudFront — a special requirement for the China region 3. Automation \u0026amp; Notifications:\nAmazon SNS: Sends email notifications about certificate issuance status, ensuring operations teams are promptly informed Amazon EventBridge: Triggers certificate renewal on a schedule, defaulting to automatic renewal every 30 days Deployment Demo Create Management Stack Creating the management stack is the first step in deploying China CloudFront SSL Plugin V2. Using an Amazon CloudFormation template, you can deploy the main stack — including Lambda functions, API Gateway, DynamoDB, and other core components — with a single click. During deployment, you need to specify a stack name and an Access Key as the API Gateway security key, ensuring only authorized users can access the certificate management features. The entire deployment process takes approximately 3–5 minutes, after which you will receive an access link to the certificate management frontend.\nCreate Certificate Project Creating a certificate project is the core step in using China CloudFront SSL Plugin V2. In the graphical management interface, you can easily create new certificate projects to request free Let\u0026rsquo;s Encrypt SSL certificates for specified domain sets. Each project supports multiple domains (comma-separated), and you can configure the notification email address and automatic renewal interval (30 days recommended). Once a project is created, the system automatically deploys a dedicated sub-stack containing a certificate issuance Lambda function and an EventBridge scheduling rule for automated certificate management.\nAttach the Auto-Issued Certificate to CloudFront Attaching the auto-issued certificate to CloudFront is the key step for enabling HTTPS access. After a certificate is successfully issued, the system automatically uploads it to IAM SSL certificate storage. You can then find and select the corresponding certificate in the CloudFront console\u0026rsquo;s distribution settings. Under \u0026ldquo;Alternate Domain Names and SSL Certificate,\u0026rdquo; enter the domain name for which you requested the certificate, then select the corresponding certificate from the custom SSL certificate dropdown to complete the binding. Once bound, subsequent automatic certificate renewals will seamlessly replace the certificate in CloudFront without any manual intervention.\nUpdate Certificate Project (Domains / Auto-Renewal Interval) The update certificate project feature allows you to flexibly adjust project configurations to adapt to business changes. By selecting a project and clicking the \u0026ldquo;Modify Project\u0026rdquo; button, you can update the domain list and adjust the SSL certificate auto-renewal interval. Each project modification triggers a new certificate issuance, ensuring configuration changes take effect immediately. The system automatically handles CloudFront certificate updates and old certificate cleanup — the entire process is transparent to the user and reliably secure.\nRe-issue Certificate / Force Certificate Update The re-issue certificate feature gives you manual control over certificate updates. When certificate issuance fails or you need an immediate certificate update, you can select the corresponding certificate from the certificate list and click the \u0026ldquo;Re-issue\u0026rdquo; button to manually trigger the certificate update process. The system re-executes the full certificate request, validation, issuance, and CloudFront update workflow, and notifies you of the result via email. This feature is particularly useful for fault recovery, emergency updates, or testing scenarios, ensuring your SSL certificates are always up to date.\nTo experience the full feature set, please refer to our solution page for deployment.\nDeploy: One-Click Deploy China CloudFront SSL Plugin V2\nTutorial: China CloudFront SSL Plugin V2 Full Tutorial\nSummary China CloudFront SSL Plugin V2 delivers a more convenient and comprehensive certificate solution for CloudFront users in the China region through its brand-new multi-project management architecture, intuitive graphical interface, and enhanced security mechanisms.\nResources and Documentation Tutorials \u0026amp; Deployment China CloudFront SSL Plugin V2 Full Tutorial\nDetailed deployment and usage guide with complete step-by-step instructions and troubleshooting\nOne-Click Deploy V2\nDeploy the latest version directly via CloudFormation template\nOpen Source Repositories China CloudFront SSL Plugin V2\nComplete V2 source code, supporting custom development and contributions\nChina CloudFront SSL Plugin V1\nFirst-generation source code for comparison and reference\nEmail the Solution Team\nContact the China CloudFront SSL Plugin solution team directly for professional support\nICP Filing Guide\nRequired ICP filing process for website deployment in the China region\nRelated AWS Service Documentation Amazon CloudFront China Region Feature Differences\nUnderstand the special requirements and limitations of CloudFront in the China region\nIAM SSL Certificate Management\nOfficial documentation for China region CloudFront SSL certificate storage\nAmazon Route 53 Domain Migration\nDetailed steps for migrating domain resolution to Route 53\nAmazon CloudFront Deployment Guide\nCloudFront Deployment Mini-Guide — Deploying Free Certificates with China Region CloudFront and SSL Plugin\nOther Technical References Let\u0026rsquo;s Encrypt Documentation\nLearn about how the Let\u0026rsquo;s Encrypt certificate authority works and its limitations\nCertbot Documentation\nDetailed usage instructions for the Certbot tool\nAmazon Route 53 DNS Validation\nTechnical documentation for the Route 53 DNS validation plugin\nContact Us Contact AWS Technical Support\nGet official professional technical support and answers\nEmail the Solution Team\nContact the China CloudFront SSL Plugin solution team directly for professional support\nOriginal: AWS Blog | GitHub\n","date":"2025-08-19T00:00:00+08:00","image":"/p/china-cloudfront-ssl-plugin-v2/images/architecture-v2.png","permalink":"/p/china-cloudfront-ssl-plugin-v2/","title":"China CloudFront SSL Plugin V2 - One-Stop Free SSL Certificate Management"},{"content":"With the rapid development of artificial intelligence, LLM models have demonstrated powerful capabilities in natural language processing, machine translation, and intelligent assistants. These models are typically developed using frameworks like PyTorch, with pre-trained results stored in specific binary formats such as PyTorch\u0026rsquo;s .pt files. However, as model sizes continue to grow, traditional file formats face challenges in storage, transmission, and loading — large file sizes, slow loading speeds, and poor cross-platform compatibility.\nTo address these challenges, GGUF (GPT-Generated Unified Format) was created. GGUF is a binary file format designed specifically for LLM models, proposed by Georgi Gerganov, the founder of the llama.cpp open-source project. It aims to improve the storage and exchange efficiency of large models through optimized data structures, compact binary encoding, and memory mapping. GGUF format is now widely used in deploying and sharing various large models, especially popular in open-source communities like Hugging Face.\nIts core features enable developers to manage and use LLM models more efficiently while reducing resource consumption and improving performance. Through conversion tools, original model pre-training results can be easily converted to GGUF format for a more efficient experience.\nIn this article, you will learn how to deploy LLM models in GGUF file format using Amazon SageMaker AI real-time inference endpoints.\nAmazon SageMaker AI Model Deployment Options Amazon SageMaker AI is a fully managed service that brings together a broad set of tools to enable high-performance, low-cost machine learning (ML) for any use case. With SageMaker AI, you can build, train, and deploy ML models at scale using notebooks, debuggers, profilers, pipelines, MLOps, and more. It supports built-in algorithms and pre-built Docker images for common ML frameworks (TensorFlow, PyTorch, ONNX, XGBoost), and provides specialized Deep Learning Containers (DLC), libraries, and tools for model parallelism and Large Model Inference (LMI).\nIf the pre-built Docker images don\u0026rsquo;t meet your needs, you can build your own Docker container (BYOC – Bring Your Own Container) for inference. To be compatible with SageMaker AI, your container must:\nHave a web server listening on port 8080. Accept POST requests to /invocations and /ping endpoints. Requests must return within 60 seconds with a maximum size of 6 MB. To deploy and run GGUF models in SageMaker AI, you need to build a custom Docker container. This approach integrates the llama.cpp project to run GGUF models for effective deployment and inference on the SageMaker AI platform.\nllama.cpp and GGUF llama.cpp is a C/C++ LLM inference project designed for local or cloud-based LLM inference with minimal setup and optimal performance across various hardware. Key advantages include:\nPure C/C++ implementation with no dependencies First-class support for Apple silicon, optimized via ARM NEON, Accelerate, and Metal frameworks AVX, AVX2, AVX512, and AMX support for x86 architectures Multiple quantization options (from 5-bit to 8-bit) for faster inference and lower memory usage Multiple GPU backend support including NVIDIA (CUDA), AMD (HIP), and Moore Threads MTT (MUSA) CPU+GPU hybrid inference, enabling partial acceleration for models larger than VRAM capacity To run in llama.cpp, models must be stored in GGUF format. You can run GGUF models through llama.cpp containers, leveraging its full capabilities. When running GGUF models in SageMaker, combining them with llama.cpp maximizes its efficient inference capabilities and multi-hardware architecture support.\nHosting GGUF Models in SageMaker AI Using BYOC The following section details how to combine GGUF with llama.cpp using Amazon SageMaker AI. We\u0026rsquo;ll demonstrate how to build a dedicated GGUF Docker container for SageMaker AI and apply it to model inference.\nUsing the Bring Your Own Container (BYOC) approach, Amazon SageMaker AI provides great flexibility. Regardless of programming language, runtime, framework, or dependencies, you can integrate virtually any model and code into the SageMaker AI ecosystem.\nThis article uses Amazon SageMaker AI Notebook to build and deploy the GGUF model runtime framework. The solution architecture is shown below.\nThe main steps are:\nFrom HuggingFace, download a GGUF model and upload it to S3. This blog uses Llama 3 8B GGUF as an example. Prepare the key BYOC files in the Notebook: Dockerfile, main.py, requirements.txt, serve, server.sh. Create a custom Docker image and push it to Amazon ECR. Create an Amazon SageMaker Model in the Notebook and deploy it to an inference endpoint. During endpoint startup, download the GGUF model from S3 to the specified location in the container. Test the endpoint by invoking inference with the SageMaker SDK. 1. Create Amazon SageMaker AI Notebook You can create a SageMaker AI Notebook instance in the AWS console, selecting an appropriate instance type and storage. Note that disk space of 30GB or more is recommended, primarily for container building and model storage.\nWhen selecting or creating an IAM role, ensure the role has permissions to push images to Amazon ECR.\nIf the permissions are missing, add the following inline policy:\n1 2 3 4 5 6 7 8 9 10 11 12 { \u0026#34;Effect\u0026#34;: \u0026#34;Allow\u0026#34;, \u0026#34;Action\u0026#34;: [ \u0026#34;ecr:CompleteLayerUpload\u0026#34;, \u0026#34;ecr:UploadLayerPart\u0026#34;, \u0026#34;ecr:InitiateLayerUpload\u0026#34;, \u0026#34;ecr:BatchCheckLayerAvailability\u0026#34;, \u0026#34;ecr:PutImage\u0026#34;, \u0026#34;ecr:BatchGetImage\u0026#34; ], \u0026#34;Resource\u0026#34;: \u0026#34;arn:aws:ecr:*:*:*\u0026#34; } 2. Build BYOC Code The complete code is available in the aws-samples repository. This article covers key code explanations only.\nTo run GGUF models in SageMaker, prepare the code with the following file structure:\n1 2 3 4 5 6 workspace |-- Dockerfile |-- main.py |-- requirements.txt |-- serve |-- server.sh The runtime trigger logic and HTTP requests are shown below.\n2.1 Dockerfile The Dockerfile defines a container environment based on the llama.cpp CUDA version, designed specifically for running GGUF models on SageMaker.\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 FROM ghcr.io/ggerganov/llama.cpp:full-cuda ENV PYTHONUNBUFFERED=1 ENV MODELPATH=/app/llm_model.bin ENV PATH=$PATH:/app ENV BUCKET=\u0026#34;\u0026#34; ENV BUCKET_KEY=\u0026#34;\u0026#34; WORKDIR /app RUN apt-get update \u0026amp;\u0026amp; apt-get install -y \\ unzip \\ libcurl4-openssl-dev \\ python3 \\ python3-pip \\ python3-dev \\ git \\ psmisc \\ pciutils COPY requirements.txt ./requirements.txt COPY main.py /app/ COPY serve /app/ COPY server.sh /app/ RUN chmod u+x serve RUN chmod u+x server.sh RUN pip3 install -r requirements.txt RUN export PATH=/app:$PATH ENTRYPOINT [\u0026#34;/bin/bash\u0026#34;] EXPOSE 8080 When building the Dockerfile, pay attention to these key environment variables:\nMODELPATH: Specifies the model filename used at startup. BUCKET and BUCKET_KEY: Define the Amazon S3 bucket name and object key for the model file. 2.2 main.py This file implements an HTTP API server for interacting with llama.cpp. Key modifications for SageMaker deployment include:\nPort configuration: main.py defaults to port 8080, connecting to llama.cpp on port 8081 Route changes: /v1/completions changed to /invocations, added /ping health check Model loading: Added update_model function for automatic S3 model download 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 def update_model(bucket, key): try: s3 = boto3.client(\u0026#39;s3\u0026#39;) s3.download_file(bucket, key, os.environ.get(\u0026#39;MODELPATH\u0026#39;)) subprocess.run([\u0026#34;/app/server.sh\u0026#34;, os.environ.get(\u0026#39;MODELPATH\u0026#39;)]) return True except Exception as e: print(str(traceback.format_exc())) return False @app.route(\u0026#39;/ping\u0026#39;, methods=[\u0026#39;GET\u0026#39;]) def ping(): return Response(status=200) @app.route(\u0026#34;/invocations\u0026#34;, methods=[\u0026#39;POST\u0026#39;]) def completion(): ... if (is_present(body, \u0026#34;configure\u0026#34;)): res = update_model(body[\u0026#34;configure\u0026#34;][\u0026#34;bucket\u0026#34;], body[\u0026#34;configure\u0026#34;][\u0026#34;key\u0026#34;]) return Response(status=200) if (res) else Response(status=500) ... 2.3 SageMaker Inference Entry Point: serve File SageMaker inference nodes execute docker run image serve by default when starting containers.\n1 2 3 #!/bin/sh echo \u0026#34;serve\u0026#34; uvicorn \u0026#39;main:asgi_app\u0026#39; --host 0.0.0.0 --port 8080 --workers 8 2.4 llama.cpp Startup Script: server.sh server.sh starts the llama.cpp service. See the llama.cpp documentation for available runtime parameters.\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 #!/bin/sh echo \u0026#34;server.sh\u0026#34; echo \u0026#34;args: $1\u0026#34; echo \u0026#34;GPU Layer: $GPU_LAYERS\u0026#34; if lspci | grep -i nvidia \u0026amp;\u0026gt; /dev/null; then echo \u0026#34;NVIDIA GPU is available.\u0026#34; NGL=\u0026#34;$GPU_LAYERS\u0026#34; CPU_PER_SLOT=1 else echo \u0026#34;No NVIDIA GPU found.\u0026#34; NGL=0 CPU_PER_SLOT=4 fi killall llama-server /app/llama-server -m \u0026#34;$1\u0026#34; -c 2048 -t $(nproc --all) \\ --host 0.0.0.0 --port 8081 -cb \\ -np $(($(nproc --all) / $CPU_PER_SLOT)) -ngl $NGL \u0026amp; 3. Model Deployment and Testing During model deployment, specify the ECR image, instance type, and corresponding environment variables.\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 container_uri = f\u0026#34;{ECR_REPOSITORY_URI}:{IMAGE_TAG}\u0026#34; instance_type = \u0026#34;ml.g5.2xlarge\u0026#34; endpoint_name = sagemaker.utils.name_from_base(\u0026#34;llama-cpp-gguf-byoc\u0026#34;) model = sagemaker.Model( image_uri=container_uri, role=iam_role, name=endpoint_name, env={ \u0026#34;MODELPATH\u0026#34;: f\u0026#34;/app/{MODEL_NAME}\u0026#34;, \u0026#34;BUCKET\u0026#34;: S3_BUCKET_NAME, \u0026#34;BUCKET_KEY\u0026#34;: MODEL_NAME, \u0026#34;GPU_LAYERS\u0026#34;: \u0026#34;32\u0026#34;, } ) model.deploy( instance_type=instance_type, initial_instance_count=1, endpoint_name=endpoint_name, ) During inference, you can pass parameters to get model output. Standard invocation:\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 def invoke_sagemaker_endpoint(endpoint_name, llama_args): response = sagemaker_runtime.invoke_endpoint( EndpointName=endpoint_name, Body=json.dumps(llama_args), ContentType=\u0026#39;application/json\u0026#39;, ) response_body = json.loads(response[\u0026#39;Body\u0026#39;].read().decode()) return response_body llama_args = { \u0026#34;prompt\u0026#34;: \u0026#34;What are the most popular tourist attractions in Beijing?\u0026#34;, \u0026#34;max_tokens\u0026#34;: 512, \u0026#34;temperature\u0026#34;: 3, \u0026#34;repeat_penalty\u0026#34;: 10, \u0026#34;frequency_penalty\u0026#34;: 1.1, \u0026#34;top_p\u0026#34;: 1, } inference = invoke_sagemaker_endpoint(endpoint_name, llama_args) print(inference[\u0026#39;choices\u0026#39;][0][\u0026#39;text\u0026#39;]) Streaming output:\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 def invoke_sagemaker_streaming_endpoint(endpoint_name, llama_args): response = sagemaker_runtime.invoke_endpoint_with_response_stream( EndpointName=endpoint_name, Body=json.dumps(llama_args), ContentType=\u0026#39;application/json\u0026#39;, ) event_stream = response[\u0026#39;Body\u0026#39;] for line in event_stream: itm = line[\u0026#39;PayloadPart\u0026#39;][\u0026#39;Bytes\u0026#39;][6:] try: res = json.loads(itm, strict=False) print(res[\u0026#34;choices\u0026#34;][0][\u0026#34;text\u0026#34;], end=\u0026#39;\u0026#39;) except: pass llama_args = { \u0026#34;prompt\u0026#34;: \u0026#34;What are the most popular tourist attractions in Beijing?\u0026#34;, \u0026#34;max_tokens\u0026#34;: 512, \u0026#34;temperature\u0026#34;: 3, \u0026#34;repeat_penalty\u0026#34;: 10, \u0026#34;frequency_penalty\u0026#34;: 1.1, \u0026#34;top_p\u0026#34;: 1, \u0026#34;stream\u0026#34;: True } invoke_sagemaker_streaming_endpoint(endpoint_name, llama_args) You can pass S3 bucket name and object key to the SageMaker AI inference instance for dynamic model replacement at runtime:\n1 2 3 4 5 6 7 8 9 10 11 12 payload = { \u0026#34;configure\u0026#34;: { \u0026#34;bucket\u0026#34;: S3_BUCKET_NAME, \u0026#34;key\u0026#34;: MODEL_NAME } } response = sagemaker_runtime.invoke_endpoint( EndpointName=endpoint_name, ContentType=\u0026#39;application/json\u0026#39;, Body=json.dumps(payload) ) print(f\u0026#34;response: {response}\u0026#34;) The inference results after deployment are shown below.\nAfter testing, if you no longer need the inference endpoint, delete the Endpoint resources to avoid unnecessary charges.\nSummary This article demonstrated how to deploy GGUF format models on Amazon SageMaker AI inference endpoints using the Bring Your Own Container (BYOC) approach via SageMaker AI Notebook. After successful deployment, you can seamlessly integrate the model with other AWS services and embed it into your applications to build feature-rich AI applications.\nReferences GGUF Specification llama.cpp Amazon SageMaker Adapting Your Own Inference Container SageMaker BYOC Examples llama.cpp API Example GenAI LLM CPU SageMaker Community AWS Article Original post: Practice Running GGUF Format Model Inference Using SageMaker AI\nGitHub repo: aws-samples/deploy-gguf-model-to-sagemaker\n","date":"2025-02-12T00:00:00+08:00","image":"/p/sagemaker-gguf-model-inference/images/architecture.jpg","permalink":"/p/sagemaker-gguf-model-inference/","title":"Deploy GGUF Models on Amazon SageMaker with llama.cpp"},{"content":"Around 2024, GPT-SoVITS quickly gained traction in the open-source speech community. It made custom voice creation—previously a highly specialized undertaking—accessible to everyday developers. The official project supports zero-shot TTS from roughly five seconds of reference audio, as well as few-shot fine-tuning with about one minute of speech. It can also use a reference voice to synthesize speech across languages, including Chinese, English, and Japanese.\nIts popularity stems not only from its output quality, but also from a WebUI that brings together data segmentation, speech recognition, text annotation, training, and inference tools. This toolchain is highly efficient for model developers. However, new challenges emerge when the system is handed to real business users: the interface is complex, model files require manual management, the frontend and backend are tightly coupled, and deployment and operations require expertise in GPUs, Linux, and model directory structures.\nThis was the starting point for MagicVoice: packaging GPT-SoVITS as a ready-to-use, manageable reference solution deployed in the customer\u0026rsquo;s own AWS account.\nFrom GPT-SoVITS\u0026rsquo;s Popularity to an AWS Solution The customer wanted to use custom voices for audiobook production and similar content workflows. The requirement went well beyond simply “reading text aloud”:\nProvide multiple characters and emotions within one system; Create character voices quickly from a small number of samples; Generate Chinese, English, or mixed Chinese-English content with the same character; Keep end users from having to understand model weights or complex inference parameters; Allow model developers to train, update, and manage voices independently; Enable rapid environment deployment, with straightforward maintenance or decommissioning after testing. The native GPT-SoVITS WebUI is built with Gradio and offers a comprehensive feature set, but it combines model development, data processing, and end-user inference in a single interface. Nontechnical users face too many options, while solution maintainers cannot readily host it as a static website on Amazon S3 and Amazon CloudFront.\nMagicVoice therefore focused on four goals:\nOne-click infrastructure deployment: Use AWS CDK to generate an AWS CloudFormation template. A user-friendly interface: Build a new frontend that exposes only essential options. Cloud-based model management: Host models in Amazon S3 to simplify the deployment of characters, emotions, and reference voices. Separation of developers and users: Developers handle training, models, and voice licensing; users simply choose a voice and generate audio. This adds a productization layer beyond merely moving the WebUI to Amazon EC2—and that layer is central to the value of the solution.\nMagicVoice Architecture on AWS The following diagram shows the overall MagicVoice architecture on AWS and its three core flows: frontend access, speech inference, and model updates.\nOverall MagicVoice architecture on AWS The architecture consists of three main components: the web frontend, the inference backend, and the model synchronization and update service.\n1. Web Frontend The frontend is built with React and AWS Cloudscape; Compiled static assets are stored in Amazon S3; Amazon CloudFront serves as the unified access point and distributes the frontend content; The interface exposes only text, character, emotion, language, speed, and a small set of advanced inference options; The “Reload TTS Service” action enters the backend event flow through Amazon API Gateway. Cloudscape offers more than visual consistency. It allows the frontend to be released independently of Gradio and the model process, so end users never need to see developer-oriented functions such as training, audio segmentation, or weight paths.\n2. Inference Backend The GPT-SoVITS inference service runs on a GPU-enabled Amazon EC2 instance; CloudFront forwards inference requests to the EC2 backend; The EC2 instance reads characters, emotions, model weights, and reference audio from the model S3 bucket; The inference API supports both standard responses and streaming output. A proof-of-concept environment can start with a g4dn.xlarge instance. Production instance sizing, however, should be benchmarked against the model version, concurrency, time to first audio output, audio duration, and GPU memory consumption.\n3. Model Synchronization and Update Service Model updates can be triggered in two ways:\nA model developer uploads or deletes model files in Amazon S3, and the resulting S3 event is sent to Amazon EventBridge; An authorized user selects the reload action in the frontend, causing Amazon API Gateway to send an event to EventBridge. EventBridge then invokes AWS Systems Manager Run Command. Using a predefined Systems Manager document, Run Command executes synchronization and reload scripts on the EC2 instance. The scripts synchronize the latest models from Amazon S3 to the inference instance and then refresh the service.\nAs a result, model developers do not need to sign in to the EC2 instance or copy weights manually. The inference instance does not need to expose SSH, and routine management is handled through Amazon S3, EventBridge, and Systems Manager.\nWhy Separate Model Developers from End Users? A custom-voice solution serves two fundamentally different groups:\nRole Responsibilities What They Do Not Need to Handle Model developer Prepare licensed source material, train models, organize directories, upload to Amazon S3, and validate voice quality The business-facing interface and routine text generation End user Select a character, emotion, and language; enter text; preview or download the result Weight files, training parameters, GPUs, or server operations This separation improves usability and clarifies responsibility for voice rights and operations. Whether voice material is properly licensed and whether a model may be used commercially should be addressed in the model release process—not decided ad hoc by end users at inference time.\nThe MagicVoice frontend therefore exposes only the options required by the business workflow:\nTTS Text; Character; Emotion; Language; Speed; Inference Batch; Top K, Top P, Temperature; Streaming; Reload TTS Service. The streamlined MagicVoice user interface built with AWS Cloudscape The Model Lifecycle: From Training to Production GPT-SoVITS models used to generate different character voices require a consistent directory structure for GPT weights, SoVITS weights, reference audio, reference text, and language metadata. The basic workflow is:\nPrepare and train a voice model in a separate training environment; Organize the model according to the MagicVoice directory convention; Upload the model directory to the model storage S3 bucket; An S3 event triggers EventBridge; EventBridge invokes Systems Manager Run Command; The EC2 instance synchronizes the model and reloads the inference service; After refreshing the character list, users can select the new voice. Training and online inference should run in separate environments. Start GPU instances on demand for model training, then publish the resulting models to Amazon S3 so that training workloads do not consume online inference capacity.\nFor consistent management of character voices and emotions, organize directories by character and model version, and store the model weights, reference audio, and inference configuration together in each directory.\nExample character model directory The infer_config.json file is the entry point for each character model\u0026rsquo;s inference configuration. It records the locations of the GPT and SoVITS weight files, while emotion_list maps emotion labels such as “default” and “angry” to the corresponding reference audio (ref_wav_path), reference text (prompt_text), and language (prompt_language). After a user selects a character and emotion in the frontend, the inference service uses this configuration to load the appropriate model weights and reference audio, eliminating the need to maintain each file path in application code.\nEach model version should include:\nAn infer_config.json inference configuration file; GPT and SoVITS model weights; Reference audio for each emotion, together with its text and language metadata; The model version and release date. Ready-to-Use Deployment with Infrastructure as Code MagicVoice uses Amazon CloudFront, Amazon S3, Amazon EC2, Amazon API Gateway, Amazon EventBridge, AWS Systems Manager, and AWS Identity and Access Management (IAM). Creating these resources manually in the console would not only slow deployment, but also make it difficult to maintain consistency across environments. This solution uses infrastructure as code (IaC) to deploy and manage the complete solution framework.\nThe infrastructure template creates and connects:\nA frontend S3 bucket; A model S3 bucket; A CloudFront distribution; A GPU-enabled EC2 instance, Amazon EBS volumes, a security group, and an instance role; An API Gateway reload API; EventBridge rules; A Systems Manager document; The required IAM roles and policies. Permissions follow the principle of least privilege: the EC2 instance can read only the designated model bucket; EventBridge can invoke only the designated Systems Manager document; Run Command targets only the intended instance; and the frontend reload API must not allow anonymous access.\nDemo: From Text Input to Speech Generation The following video demonstrates the complete MagicVoice workflow in about three minutes, including character and parameter selection, speech generation, and output preview.\nDownload the MagicVoice demo video If your browser does not support embedded playback, you can download the demo video directly.\nConclusion GPT-SoVITS lowered the barrier to few-shot voice cloning and cross-lingual speech synthesis. MagicVoice takes the next step by packaging these capabilities as a solution that can be rapidly deployed, easily used, and centrally managed within a customer\u0026rsquo;s AWS account.\nThe value of MagicVoice lies not in any single model parameter, but in its end-to-end design for real-world usage:\nBuild a clean, intuitive frontend with AWS Cloudscape; Host and distribute the frontend through Amazon S3 and Amazon CloudFront; Run the GPT-SoVITS inference service on a GPU-enabled EC2 instance; Centrally manage characters, emotions, and model files in Amazon S3; Automate model synchronization and service reloads with Amazon EventBridge and AWS Systems Manager; Standardize repeatable deployment with AWS CDK and AWS CloudFormation; Separate model development from routine use to reduce complexity for end users. Together, these design choices transform the developer-oriented GPT-SoVITS WebUI into an AWS TTS reference architecture that is easier to deploy, operate, and maintain.\nReferences GPT-SoVITS GitHub Amazon CloudFront Documentation Using Amazon S3 with Amazon EventBridge AWS Systems Manager Run Command AWS CDK Documentation AWS Pricing Calculator ","date":"2024-12-01T00:00:00+08:00","permalink":"/p/aws-magicvoice-gpt-sovits-solution/","title":"From GPT-SoVITS to AWS MagicVoice: Building a Custom-Voice TTS Solution"},{"content":"CORS, or Cross-Origin Resource Sharing, is an HTTP header-based mechanism that allows servers to indicate which external origins (domains, protocols, or ports) can access their resources. CORS addresses the inconvenience caused by the same-origin policy — a browser security mechanism that restricts web pages from loading resources from different origins to prevent malicious websites from stealing sensitive data. However, this restriction also blocks legitimate cross-origin requests. Complex applications often reference third-party APIs and resources in their client-side code, and CORS is needed when the client domain does not match the server domain. Through CORS, browsers can safely perform cross-origin data transfers, bypassing the limitations of the same-origin policy. CORS allows client browsers to check with third-party servers whether a request is authorized before any data is transferred. Due to the complexity of CORS configuration, developers often set overly permissive cross-origin access permissions — for example, using \u0026ldquo;*\u0026rdquo; in allowed headers to permit all access — which can compromise application security.\nAmazon API Gateway is a fully managed service that helps developers easily manage APIs at any scale. It is commonly used for backend service management and routing. Therefore, configuring CORS on API Gateway is a very common requirement. In Amazon API Gateway, different API types have different CORS configuration methods, which adds to the complexity of CORS configuration.\nThis article explains how to configure cross-origin resource sharing in Amazon API Gateway\u0026rsquo;s REST API and HTTP API, with a focus on the differences between REST API and HTTP API in CORS configuration, as well as how to configure CORS when authorization is enabled. By reading this article, you will master the CORS configuration techniques in Amazon API Gateway, enabling cross-origin access configurations that meet the principle of least privilege.\nHow CORS Works CORS is an HTTP header-based mechanism where servers use header information to restrict access. CORS works primarily through the following key HTTP headers:\nOrigin: Indicates the request origin. Access-Control-Allow-Origin: Specifies which origins can access the resource. Access-Control-Allow-Methods: Lists the HTTP methods allowed to access the resource. Access-Control-Allow-Headers: Indicates which custom request headers are allowed. Access-Control-Allow-Credentials: Indicates whether credentials such as cookies are allowed. Access-Control-Max-Age: Indicates how long preflight request results can be cached. Based on the complexity of the request, CORS divides them into two categories:\nSimple requests: No preflight is needed. These requests use GET/POST/HEAD methods and only use specific safe headers (such as Accept, Content-Type). Non-simple requests: Preflight is required. Any cross-origin request that is not a simple request is considered a non-simple request. Before sending the actual request, the browser first sends an OPTIONS request to confirm whether the server allows the actual request. This preflight mechanism prevents unauthorized cross-origin operations from having side effects on server data. For non-simple requests, the server relies on the browser to send a CORS preflight or OPTIONS request. A complete request flow is as follows:\nThe complete CORS flow for non-simple requests:\nClient application initiates the request Browser sends the preflight request Server returns the preflight response Browser sends the actual request Server returns the actual response Client receives the actual response Introduction to API Gateway Amazon API Gateway is a fully managed service that helps developers easily create, publish, maintain, monitor, and secure APIs at any scale. Without the need to maintain the underlying infrastructure, API Gateway can accept and process thousands of concurrent API calls. API Gateway supports both RESTful and WebSocket API types, as well as multiple backend integration types such as containerized services, serverless workloads, and HTTP endpoints. Other key features of API Gateway include traffic management, CORS support, authorization and access control, throttling, monitoring, and API version management.\nREST API vs HTTP API REST API and HTTP API are both RESTful API products of Amazon API Gateway. Their differences are as follows.\nFeatures REST API\u0026rsquo;s unique features include:\nAPI key support Per-client throttling Request validation AWS WAF integration Private API endpoints HTTP API is designed with a minimalist feature set. Its characteristics include:\nAutomatic deployment Default stage support Performance and Pricing Because HTTP API has a more streamlined feature set, it offers faster speeds and lower prices.\nConfiguring CORS in API Gateway To resolve cross-origin issues in Amazon API Gateway, you need to perform CORS configuration. API Gateway will automatically use the OPTIONS method and attempt to add CORS headers to existing method integration responses, which helps you handle preflight requests and actual responses. In Amazon API Gateway, REST API and HTTP API have different CORS configuration methods.\nREST API CORS Configuration As shown in the following figure, the REST API has a default / resource, under which we created a POST method integrated with a Lambda function as the backend service. To configure CORS for the POST method under the / resource, we need to go back to the resource overview page and click Enable CORS. On the Enable CORS page, first configure the allowed methods for access control. To correctly respond to preflight requests, the OPTIONS method is enabled by default. We select the POST method that needs CORS configuration. Then, we configure the allowed headers and origins for access control — the specific allowed values depend on your backend application. Click Save after configuration. After saving, on the POST method\u0026rsquo;s integration response page, you can see that in the header mapping, the Access-Control-Allow-Origin mapping value is the allowed origin configured in the previous step. In the resource list, we can also see that after enabling CORS, API Gateway automatically created an OPTIONS method for us. This method is used to correctly respond to preflight requests. The OPTIONS method\u0026rsquo;s integration type is mock integration, which returns a 200 status code for requests and returns all relevant preflight response headers. The header mapping values are determined by the settings in step 3. Testing a cross-origin POST request from the allowed origin endpoint configured in step 3, we can see that for both the preflight request and the actual request, the REST API returns the corresponding headers. For non-root paths, you can also check CORS (Cross-Origin Resource Sharing) when creating the resource, so that API Gateway automatically creates an OPTIONS method under this resource to handle preflight requests. Note that the OPTIONS method created using this approach will accept cross-origin requests from all origins and all methods by default. If you need to tighten the permissions, you can click Edit in the upper right corner to modify it.\nAfter checking CORS (Cross-Origin Resource Sharing) when creating the resource, you still need to click Enable CORS in the upper right corner of the resource overview page (following the same method as step 3) to configure the CORS-related headers for the specific request method (such as POST).\nCORS Configuration with Authorization You can integrate Lambda authorizers or Cognito authorizers with your REST API. When enabling authorization, be sure to only enable it for the methods that need it — do not enable authorization for the OPTIONS method, otherwise preflight requests (which are unauthorized) will result in 401 errors.\nEnable authorization for the POST method.\nIf authorization is enabled for the OPTIONS method, preflight requests will fail with errors.\nDo not enable authorization for the OPTIONS method.\nHTTP API CORS Configuration In this section, we continue to use configuring CORS for the POST method under the / resource as an example to demonstrate how to configure CORS for HTTP API.\nHTTP API CORS configuration is relatively simple because once you enable CORS for your HTTP API, API Gateway will automatically respond to preflight requests from browsers and automatically add CORS-related headers to your backend responses. You will not see the configuration of the OPTIONS method that API Gateway uses to automatically respond to preflight requests in your API resources, nor will you see the response header configuration for the POST method.\nThe following are the detailed steps to enable HTTP API CORS:\nGo to the HTTP API page, click CORS in the left navigation bar, then click Configure in the upper right corner. On the CORS configuration page, enter the allowed origins, headers, and methods for access control. In our example, we need to allow POST method access. Depending on your needs, you can also optionally configure exposed headers, max age, and credentials. After configuration, click Save in the lower right corner. After configuration, we cannot see the OPTIONS method configuration on the HTTP API routes page. Testing a cross-origin POST request from the allowed origin endpoint of the HTTP API, we can see that both the preflight OPTIONS request and the actual POST request receive correct responses. This is because API Gateway handles the HTTP API\u0026rsquo;s response to preflight requests and adds the CORS-related headers for us. CORS Configuration with Authorization Similar to REST API, HTTP API supports authorization for specific methods through Lambda, JWT, and IAM authorizers. If you want to enable CORS for an HTTP API with integrated authorizers, in most cases, HTTP API will automatically handle preflight requests for you. Therefore, no special configuration is needed — simply follow the steps above to enable CORS for an HTTP API with integrated authorizers. The only exception is when you create an authorized ANY method (as shown below). In this case, note that preflight requests will be handled by the ANY method rather than by HTTP API. Since preflight requests do not contain authorization information, the authorized ANY method will not return the correct status code and CORS headers, and the preflight request will fail with a 401 error.\nIn this case, there are two solutions:\n(Recommended) Create a specific route for each method and resource as needed, and avoid using the ANY method. For example, in our case, we only need to create a route for the POST method. Create an unauthorized OPTIONS method route under the same resource path, and add any backend integration to the OPTIONS method (as shown below). This way, the unauthorized OPTIONS route will capture preflight requests. Summary This article introduced the CORS configuration methods for REST API and HTTP API in Amazon API Gateway, with special attention to how to configure both API types to ensure preflight requests are correctly responded to when authorization is enabled. The differences in CORS configuration between the two API types are as follows:\nAPI Type CORS Configuration Method Configuration Features Authorization Notes REST API Configure CORS for specific routes in the REST API by clicking Enable CORS in the upper right corner of the route. You can see the OPTIONS method used to respond to preflight requests and its response header settings under the configured route. You can also see the CORS header settings in the response of the methods that allow cross-origin access. Do not enable authorization for the OPTIONS method. HTTP API Configure CORS for the entire HTTP API by clicking CORS in the left navigation bar to enter the CORS configuration page. Preflight requests are automatically handled by API Gateway, and the automatically responding OPTIONS method configuration is not visible in the console. CORS headers are automatically added by API Gateway, and the CORS header settings are also not visible in the response of the methods that allow cross-origin access. Avoid using the ANY method. If you must use it, create an additional unauthorized OPTIONS method for handling preflight requests. To enable CORS for other AWS resources, refer to:\nEnable CORS for CloudFront Enable CORS for Lambda Function URLs Enable CORS for S3 Static Website Hosting Original article: Amazon API Gateway CORS Configuration - AWS Blog\n","date":"2024-10-28T00:00:00+08:00","permalink":"/p/api-gateway-cors-configuration/","title":"API Gateway CORS Configuration Guide"},{"content":"Generative AI (GenAI) has risen rapidly since 2022, sweeping the globe and demonstrating enormous potential across multiple domains — text-to-image, text-to-text, image-to-image, and more. Models like Stable Diffusion and DALL-E can generate realistic images from natural-language descriptions, opening new possibilities for creative design and visual arts. Meanwhile, large language models such as Claude and GPT enable natural, fluent conversational interactions, empowering content creation and Q\u0026amp;A applications.\nWordPress is a widely used open-source content management system (CMS) ideal for creating and managing all types of websites — blogs, corporate sites, personal pages, and online stores. First released in 2003, it was designed to give users an easy-to-use platform for publishing content, even without a technical background.\nNow, leveraging the powerful AI capabilities of AWS, you can experience an intelligent AI writing assistant directly inside WordPress to accelerate your content creation. The newly launched WordPress GenAI Plus solution seamlessly integrates Claude 3 (via Amazon Bedrock) and Stable Diffusion into the WordPress editor. Simply provide a prompt or topic direction, and the AI will automatically generate article content and images. You can iterate as many times as needed until you achieve the ideal result.\nThe main features provided by WordPress GenAI Plus writing assistant include:\nText Generation: Generate articles based on user prompts Image Generation: Generate images based on user prompts Translation: Currently supports Chinese, English, French, Japanese, and Korean as target languages; source language is unrestricted Grammar Check: Provides grammar correction suggestions for selected English paragraphs (English only) This solution supports one-click deployment via an Amazon CloudFormation template. By deploying the stack, users get the complete infrastructure — WordPress site, database, CDN, and AI capabilities — greatly simplifying setup and usage.\nArchitecture Overview The WordPress GenAI Plus solution can be deployed in any AWS global region. It offers both a two-tier architecture (separating web and database layers) and a traditional LNMP (Linux, Nginx, MySQL, PHP) all-in-one architecture. The two-tier architecture is shown below:\nArchitecture highlights: Two-tier (web + data), WordPress on public subnet, RDS on private subnet, multi-AZ option, CloudFront CDN, Lambda + Bedrock integration for GenAI capabilities. EC2, RDS, and Lambda can be deployed in any region; Bedrock is available in us-east-1 or us-west-2.\nDeployment Process Model Access Preparation Before getting started, you need to request model access permissions in Amazon Bedrock.\nSelect the Bedrock service in the AWS global console Select the model deployment region (us-east-1 or us-west-2) in the top-right corner In the left sidebar, select \u0026ldquo;Model access\u0026rdquo; Click the \u0026ldquo;Manage model access\u0026rdquo; button Check the boxes for SDXL1.0, Claude 3 Sonnet, and Claude 3 Haiku, then click \u0026ldquo;Save changes\u0026rdquo; Wait for permission to be granted (status changes to \u0026ldquo;Access granted\u0026rdquo;) Create Key Pair A key pair allows you to securely connect to your Amazon EC2 instance via SSH. Before deployment, make sure you have created a key pair.\nIf you haven\u0026rsquo;t created one yet, click here to create a key pair.\nConfirm the deployment region, enter a key pair name, click \u0026ldquo;Create key pair\u0026rdquo; and save it securely. Create CloudFormation Stack Click the link above to enter the stack deployment page.\nClick to deploy\nConfirm the deployment region in the top-right corner (must match your key pair region), then specify the following parameters:\nCustom stack name EC2 instance type EC2 disk size EC2 key pair Database username Database password (min 8 chars, no /, quotes, or @) Database instance type Database storage size Multi-AZ deployment option Bedrock deployment region Click Next.\nOn step 3 \u0026ldquo;Configure stack options\u0026rdquo;, click Next On step 4, check the IAM acknowledgments and CAPABILITY_AUTO_EXPAND, then click Submit Wait about 10 minutes for the stack status to become CREATE_COMPLETE Check the Outputs tab for GenAI Function URL, WordPress install URL, admin URL, and site URL Start Using WordPress AI Capabilities Initialize WordPress After deployment, find the InstallWordPress field in the CloudFormation stack outputs and open the URL to configure WordPress.\nIn the one-click deployment, database information is pre-configured. You only need to set up your site title, username, and password, then click \u0026ldquo;Install WordPress\u0026rdquo; and log into the admin panel.\nEnable the GenAI Plugin In the WordPress admin panel, click \u0026ldquo;Plugins\u0026rdquo;, find \u0026ldquo;Amazon AI writing assistant\u0026rdquo; and click Activate.\nThe Lambda URL and Region are pre-configured. Verify and click Save.\nExperience GenAI Capabilities In the WordPress admin, click \u0026ldquo;New → Post\u0026rdquo;.\nIn the editor body, type /ask to trigger the Ask AI plugin. Click it to start using the AI features.\nYou can enter text-to-text or text-to-image prompts in Chinese or English in the popup input box.\nSee the demo below:\nThe GenAI plugin also supports translation and grammar checking:\nTranslation: Enter text in any language, click the pen icon in the floating toolbar → Translate Text. Target language is set in the plugin configuration page. Supported: ZH_CN, EN_US, FR, JA, KO.\nGrammar Check: For text you want to correct, click the pen icon in the floating toolbar → Correct Text.\nAlternative Architecture You can configure your own domain name in Amazon CloudFront, use Certificate Manager to request a free public certificate for HTTPS, and update the site address in the WordPress admin panel.\nThis solution also supports a traditional LNMP all-in-one WordPress architecture:\nDeploy the LNMP architecture: Click to deploy\nSummary Through this tutorial, you can deploy WordPress GenAI Plus on AWS with one click, integrating the power of generative AI into the WordPress editor for a brand-new AI-powered content creation experience.\nRelated Resources:\nAWS AIGC Original article: WordPress GenAI Plus: Accelerate Your Website Content Creation with Generative AI\n","date":"2024-04-29T00:00:00+08:00","permalink":"/p/wordpress-genai-plus/","title":"WordPress GenAI Plus - AI Content Generation Plugin"},{"content":"This article applies to AWS China Region services. You will learn how to use Amazon CloudFront in the China Region to accelerate and distribute traffic from websites deployed on EC2, and use the China CloudFront SSL Plugin to deploy free SSL certificates to protect your site. The plugin helps you generate, renew, and download free SSL certificates in the AWS China Regions, with Amazon CloudFront integration and automatic certificate renewal. You can also refer to the EC2-CloudFront integration section for configuring CloudFront to distribute EC2 website traffic in AWS Global Regions.\nWhy Choose Amazon CloudFront? Amazon CloudFront is a Content Delivery Network (CDN) service provided by AWS. Using a CDN reduces website load times, lowers bounce rates, and increases traffic and revenue, while also reducing the load on origin servers, improving website stability, security, availability, and reliability. Amazon CloudFront securely delivers data, videos, applications, and APIs to customers globally with low latency and high transfer speeds in a developer-friendly environment, and integrates seamlessly with Amazon S3, Elastic Load Balancer, Amazon EC2, and more.\nAmazon CloudFront not only accelerates your website and reduces origin server load, but also lowers the data transfer costs for traffic leaving your AWS-hosted website to the internet. For example, compared to EC2\u0026rsquo;s outbound data transfer costs, using Amazon CloudFront in the AWS China Regions can help you reduce outbound data transfer costs by at least 67%. For specific pricing, refer to the AWS China Region official website EC2 Data Transfer Pricing and CloudFront Data Transfer Pricing.\nConsiderations for Using CloudFront in China Regions ICP Filing and Domain Registration: According to relevant laws and regulations, if you need to host a website in mainland China, you must first complete ICP filing. Domains without ICP filing cannot serve web content. Please prepare an ICP-filed domain. Refer to the AWS China ICP Filing Support Documentation for more details on obtaining the required ICP filing for your domain.\nCloudFront Provided Domain: CloudFront automatically assigns a *.cloudfront.cn domain. However, due to ICP filing requirements, you cannot directly use this domain for website services in China. You must add an ICP-filed domain as an alternate domain name (also known as CNAME) to your CloudFront distribution, and then use the alternate domain name to access your website.\nCloudFront SSL/TLS Certificate Integration: Amazon CloudFront in the China Regions does not currently support Amazon Certificate Manager. If you need to use SSL/TLS certificates with CloudFront, you can obtain them from third-party certificate authorities and import SSL/TLS certificates. You can also use the China CloudFront SSL Plugin to obtain free SSL/TLS certificates, which will be covered in detail in the \u0026ldquo;Deploy Free Certificates with China CloudFront SSL Plugin\u0026rdquo; section of this article.\nFeature Differences Between China and Global Regions: Amazon CloudFront in the China Regions does not currently support Lambda@Edge, Amazon WAF, and other features. See the documentation for more details.\nPrerequisites To complete all sections of this article and get a consistent experience with AWS services, please ensure you meet the following prerequisites.\nYour AWS China Region account has completed ICP filing, with ports 80/443 open You have an ICP-filed domain Use Amazon Route 53 as your DNS service. If you haven\u0026rsquo;t migrated your DNS to Amazon Route 53 yet, see the reference documentation Integrating EC2 with CloudFront In the following sections, you will launch an EC2 instance, set up a web server, integrate EC2 with CloudFront, and deploy a free SSL certificate using the China CloudFront SSL Plugin.\nYou will also learn some tips for using EC2 and CloudFront, such as using Elastic IP to fix your EC2 public DNS hostname for CloudFront origins, or using AWS-managed prefix lists to enhance EC2 security.\nThe deployment architecture is shown below:\nCreate EC2 and Install Web Server In this section, you will create an EC2 instance with a web server, then bind an Elastic IP to fix the EC2 public DNS hostname.\n1. Launch EC2 Instance You can launch an EC2 instance from the EC2 console.\nName your instance, e.g., \u0026ldquo;web-server\u0026rdquo;.\nYou can keep the default AMI and instance type.\nAMI: Amazon Linux 2023 Instance type: micro Under \u0026ldquo;Key pair\u0026rdquo;, select an existing key pair or create a new one for subsequent system administration.\nFor network settings, ensure your EC2 instance is deployed in a public subnet, and check \u0026ldquo;Allow HTTP traffic from the internet\u0026rdquo; to make port 80 accessible from the internet.\nExpand the \u0026ldquo;Advanced details\u0026rdquo; section at the bottom:\nAt the bottom of the page under \u0026ldquo;User data\u0026rdquo;, paste the following script to install a web server on first boot. Then click \u0026ldquo;Launch instance\u0026rdquo; to start the instance.\n1 2 3 4 #!/bin/bash yum install -y httpd systemctl enable httpd systemctl start httpd 2. Create Elastic IP and Associate with EC2 Elastic IP is a static IPv4 address designed for cloud computing. Using an Elastic IP ensures your EC2 instance\u0026rsquo;s public IP address and public DNS hostname remain unchanged. In this section, you will learn how to associate an Elastic IP with your EC2 instance and access your site using the EC2 instance\u0026rsquo;s public DNS hostname.\nFind Elastic IP under \u0026ldquo;Network \u0026amp; Security\u0026rdquo; in the EC2 console left menu.\nClick \u0026ldquo;Allocate Elastic IP address\u0026rdquo; in the upper right, then click \u0026ldquo;Allocate\u0026rdquo; to obtain an Elastic IP.\nSelect your Elastic IP, click the \u0026ldquo;Actions\u0026rdquo; button in the upper right, and choose \u0026ldquo;Associate Elastic IP address\u0026rdquo;.\nSelect your previously created EC2 instance and click \u0026ldquo;Associate\u0026rdquo; to ensure the EC2 instance\u0026rsquo;s public IP address remains stable.\nClick the \u0026ldquo;Instances\u0026rdquo; menu on the left to return to the instance list, select your instance, and copy the public IPv4 DNS.\nAccess the public DNS hostname in your browser to verify the web server is installed. You can see the site is currently using port 80 without an SSL/TLS certificate.\nIn the following sections, you will use this hostname as the CloudFront origin to divert website traffic from EC2 to Amazon CloudFront.\nCreate CloudFront Distribution In this section, you will create a CloudFront distribution and associate it with the previously deployed EC2 instance, routing traffic through CloudFront to accelerate content delivery.\n1. Create CloudFront Distribution and Associate EC2 Next, you will quickly set up a CloudFront distribution. Go to the CloudFront console and create a distribution:\nOn the CloudFront configuration page, you will see the basic configuration elements that a CloudFront distribution requires:\nOrigin – The origin server, supporting multiple AWS services including but not limited to S3, EC2, ELB, API Gateway, as well as third-party origins Cache Behavior – Define caching behavior through path matching, enable transfer compression, allowed request methods, access control, etc. Settings – Alternate domain names (CNAME), SSL certificate, default root object, logging, etc. For the origin, use the EC2 public DNS (with Elastic IP) as the origin domain. Ensure the origin protocol is HTTP.\nFor the default cache behavior, you can keep the default settings:\nNote: Due to compliance requirements, the default CloudFront distribution domain in the Beijing/Ningxia regions cannot be accessed directly. You must complete domain ICP filing and set up CNAME DNS resolution before access is possible.\nIn the settings section, enter your ICP-filed domain as the alternate domain name (CNAME):\nAfter creation, wait for deployment to complete. Once deployed, check your alternate domain name — if the domain has passed ICP filing, you should see a \u0026ldquo;green checkmark\u0026rdquo;.\nAfter deployment, go to Route 53 (or your DNS provider) to update the DNS configuration. Using Route 53 as an example, enter the corresponding domain\u0026rsquo;s hosted zone and create a new record.\nFill in the DNS record:\nAfter completing the DNS update, open your browser and access the ICP-filed domain:\nNote: If you encounter a 502 error, check whether EC2 has an SSL certificate installed or whether the origin port is correct. See the documentation. If you encounter a 403 error, ensure you are accessing via the ICP-filed domain.\n2. Enhance EC2 and Website Security In this section, you will use AWS-managed prefix lists to enhance EC2 security. You can use the Amazon CloudFront managed prefix list to restrict inbound HTTP/HTTPS traffic to only the IP addresses of CloudFront origin-facing servers.\nSelect your instance, go to the EC2 security group, and edit the inbound rules: add an HTTP rule, enter \u0026ldquo;cloudfront\u0026rdquo; in the source field, select the com.amazonaws.global.cloudfront.origin-facing prefix list, and remove the existing 0.0.0.0/0 rule.\nYou can also associate SSL/TLS certificates with CloudFront to enhance website security. In the following section, you will deploy free SSL certificates using the China CloudFront SSL Plugin.\nDeploy Free Certificates with China CloudFront SSL Plugin Before starting, please confirm once again that you are using Amazon Route 53 for DNS resolution. This section covers the deployment process only. For more details, see the China CloudFront SSL Plugin.\n1. Initialize Deployment Deploy via CloudFormation. Click the link to launch the stack in the CloudFormation console.\n2. Enter Deployment Parameters Specify stack details with the following parameters:\nStack Name: Name your stack Email: Enter your email for SNS email notifications (only one email supported) Domain Name: Enter the domain names for the SSL certificate. Supports wildcard domains and multiple domains (comma-separated) SSL Renew Interval Days: Enter the certificate renewal interval. Let\u0026rsquo;s Encrypt certificates are valid for 90 days; enter a number between 1 and 89. Recommended default: 80 days. 3. Confirm Deployment Review the deployment details on the current page, check the \u0026ldquo;I acknowledge\u0026rdquo; box at the bottom, and click Submit.\nAfter submission, you will see resources being created in the stack events tab. Wait approximately 3 minutes.\n4. Subscribe to SNS Notifications Promptly During the stack deployment process, check your email promptly. You will receive an SNS subscription confirmation request from no-reply@sns.amazonaws.com. Please click the confirmation link as soon as possible.\nSuccessful subscription confirmation:\n5. Check Stack Deployment Progress When the stack status changes to green CREATE_COMPLETE, the deployment is finished.\nCheck the \u0026ldquo;Outputs\u0026rdquo; tab for quick links:\nCloudfrontConsole: Access the CloudFront console to quickly bind the issued certificate ManagementWebURL: Access SwaggerUI to view or delete existing SSL certificates in IAM S3BucketURL: Access the S3 console to download the issued SSL certificates 6. Bind SSL Certificate in the Amazon CloudFront Console After stack deployment is complete, an SSL certificate will be automatically requested for your domain. If you have subscribed to the SNS topic, you will receive an email notification confirming the certificate has been issued. The certificate name consists of the stack name and expiry time, e.g., Certbot-2023-11-14-1540.\nOpen the CloudFront console, select your distribution, and find the option to edit alternate domain names and SSL certificate.\nSelect the corresponding SSL certificate from the custom SSL certificate dropdown, then save changes.\nAfter deployment, you can access your CloudFront-accelerated site via HTTPS in the browser and verify the SSL certificate issued by Let\u0026rsquo;s Encrypt, valid for 90 days.\nFor more information on using the China CloudFront SSL Plugin, see the plugin documentation.\nSummary Through this article, you have learned the basics of Amazon CloudFront and how to divert website traffic deployed on EC2 to CloudFront for acceleration and cost savings. You have also learned to use AWS-managed prefix lists in EC2 security groups to ensure your EC2 only accepts traffic originating from CloudFront, and to deploy free SSL certificates using the China CloudFront SSL Plugin to protect your site with HTTPS.\nReferences China CloudFront SSL Plugin Amazon CloudFront Introduction Amazon CloudFront China Region Differences Network Acceleration with Amazon CloudFront in China Original Post: Amazon CloudFront Deployment Mini-Guide (Part 8) - Deploy Free Certificates with China CloudFront and CloudFront SSL Plugin\nGitHub: aws-samples/China-CloudFront-SSL-Plugin\n","date":"2023-11-15T00:00:00+08:00","image":"/p/cloudfront-ssl-plugin-deployment-guide/images/architecture.png","permalink":"/p/cloudfront-ssl-plugin-deployment-guide/","title":"China CloudFront SSL Plugin Deployment Guide"},{"content":"Background Over the past few months, there has been growing interest in combining Stable Diffusion with ControlNet to create artistic QR codes. This post was originally developed as part of an AWS workshop demonstrating how to deploy and use Stable Diffusion on AWS infrastructure.\nThis post shares practical tips for working with Stable Diffusion and walks through the best practices for generating artistic QR codes.\nWe will use QR codes as ControlNet input, integrating QR code data points into artistic images while keeping them scannable by QR code readers. With this technology, you can transform any QR code into a unique piece of art, expressing and conveying information in an entirely new way. Here are some examples:\nStable Diffusion Practical Tips As the ancient Chinese saying goes: \u0026ldquo;The beginning is always the hardest\u0026rdquo; and \u0026ldquo;Seek breadth while perfecting the details.\u0026rdquo; These correspond to the two most common challenges when working with Stable Diffusion: first, how to choose the right prompt strategy to generate images that meet expectations; and second, how to fine-tune image details so the final output meets production-quality requirements.\nBased on our experience helping users work with Stable Diffusion, we have compiled the following best practices for reference.\nPrompt Engineering As Stable Diffusion versions continue to evolve and AI\u0026rsquo;s understanding of semantics gets closer to \u0026ldquo;common sense,\u0026rdquo; the requirements for effective prompts are becoming increasingly demanding. Many common prompt misconceptions can sometimes have adverse effects on image generation.\nBasic Concepts Prompts are divided into positive prompts (what you want) and negative prompts (what you don\u0026rsquo;t want), telling the AI what to include and what to exclude.\nCommon Misconceptions Precision over quantity — describing a scene with the shortest words is more effective than natural language. Quality-improving descriptors should not be mindlessly stacked; more is not better. Common starters like \u0026ldquo;masterpiece\u0026rdquo; and \u0026ldquo;best quality\u0026rdquo; often become dead weight in prompts. These words were meaningful in the NovelAI era, when they were heavily used during model training for image evaluation. However, after continuous model refinement by authors on Civitai, these prompts barely show their intended effect in modern models. Adjusting Prompt Weights The default weight of each token is 1, decreasing from left to right. Prompt weights significantly affect the generated image. Use parentheses + colon + number to specify weight, e.g., (one girl:1.5). Mind the Prompt Order Landscape tags first = smaller characters; character tags first = larger characters or half-body shots. Choose the correct order and syntax for prompts to more effectively render the desired scene. Emojis in Prompts Prompts support emojis, and they work with good expressiveness. For specific facial expressions or actions, adding emojis can achieve the desired effect. To prevent semantic drift, prefer emojis and minimize unnecessary complex syntax. Recommended Camera Angle Prompts Parameter Description extreme closeup Face close-up close up Head medium close up ID photo medium shot Half body cowboy shot No legs medium full shot No feet full shot Full body Image Optimization Often we generate an image that\u0026rsquo;s not quite satisfactory and want to further optimize it, but don\u0026rsquo;t know where to start. Here are some best practices for parameter tuning:\nWhich Parameters to Adjust CFG Scale: The correlation between the image and the prompt. Higher values mean greater prompt influence and closer adherence to the prompt. CFG 2–6: Creative but may be too distorted, not following the prompt. Fun for short prompts. CFG 7–10: Recommended for most prompts. CFG 10–15: Use when the prompt is detailed and clear. CFG 16–20: Not recommended unless the prompt is very detailed. CFG \u0026gt;20: Almost unusable. Sampling Steps: More steps mean smaller, more precise adjustments per step, but proportionally increase generation time. For most samplers, more iterations produce better results, but beyond 50 steps, improvements become negligible. Sampling Method: Different methods have different optimal step counts; comprehensive comparison is needed. Euler a: Creative; different step counts produce different images. An efficient method for quickly testing prompt effects. DPM2 a Karras: Good for realistic models, hard to control after 30 steps. DPM++ 2M Karras: Excellent at high step counts, more details. DDIM: Fast convergence but low efficiency; good for inpainting. Different model and sampler combinations produce different results; the above is for reference only. When choosing sampling methods, it\u0026rsquo;s best to use X/Y/Z plots for comparison. Seed: The random seed often has a huge impact on composition and is the main source of randomness in SD. With the same seed and all other parameters fixed, you can reproduce (nearly) identical images. Once you find a suitable composition, fix the seed and fine-tune details — this is the recommended approach. How to Find Optimal Parameters Use X/Y/Z plots to clearly compare results under different parameters, quickly locate suitable parameter ranges, and perform further generation control.\nImage Size Optimization Image quality is not directly tied to image size. However, size does affect the subject and content to some extent. When the output size is too wide, multiple subjects may appear. Sizes above 1024 may produce undesirable results, and GPU memory pressure becomes significant. Small resolution + upscaling is recommended. Optimizing Multi-Character and Wide-Format Generation Using txt2img alone cannot effectively specify individual character features in multi-character scenarios. The recommended approach is to create a draft + img2img or ControlNet. For wide-format single-character generation, draft a sketch with color blocking to determine the main subject, or use ControlNet\u0026rsquo;s OpenPose for character skeleton. For multi-character scenes, use ControlNet\u0026rsquo;s OpenPose to specify character count; this also works for three-view drawings of the same character. Hand Repair Send the image to img2img inpaint with similar prompts, placing \u0026ldquo;hand\u0026rdquo; prompts at the front. Set denoising strength based on how much you want hand features to change (below 0.25 if you just want completeness), keeping steps and CFG the same as txt2img. For more precise hand control, find a satisfactory hand reference image and use ControlNet\u0026rsquo;s Canny or OpenPose_hands preprocessor + model combined with inpaint.\nFace Repair When drawing images with small character subjects, facial distortion frequently occurs. Especially in the artistic QR code generation process described later, faces often break due to QR code data points. For facial inpainting, the ADetailer plugin is recommended. It uses the YOLO algorithm for object detection — we configure it to detect character faces and provide prompts and models for facial inpainting. The plugin performs localized inpainting at detected face locations to complete the repair. ADetailer can handle both face and hand detection and repair, and can also reference LoRA models for localized inpainting.\nGenerating Artistic QR Codes with ControlNet Step 1: Optimize the QR Code A QR code is a pattern of black and white geometric shapes distributed in 2D space that records symbolic data. There are multiple encoding methods; we use the most universal and fundamental one: QR Code.\nThe input QR code is one of the most important factors when generating artistic QR codes with SD. We mainly care about two characteristics:\n1. Information contained in the QR code\nRegardless of the encoding method, the more character information a QR code carries, the more complex its visual black-and-white structure becomes. Complex structures heavily constrain artistic creativity during generation. Therefore, we first need to simplify the content length.\nFor the most common use case — web links — shorten the URL first. There are many URL shortening tools available; choose freely. Note that within mainland China, use platforms with registered domain names, otherwise links may be blocked by WeChat, browsers, etc.\n2. How the QR code is presented\nWith technological development, QR codes no longer only support black and white square patterns; both positioning points and modules support diverse presentation styles.\nIn practice, try different module styles to achieve the desired generation effect. The following images show how different QR code styles affect the final result:\nGeneration parameters:\n1 2 3 4 5 6 7 8 Prompt: mountain, green grassland, sky, cloud, bird, blue sky, no human, day, wide shot, flying, border, outdoors, white bird, scenery Negative prompt: easynegative Steps: 40, Sampler: DPM++ 2M Karras, CFG scale: 6, Seed: 3943213078, Size: 872x872, Model hash: 876b4c7ba5, Model: cetusMix_Whalefall2, Clip skip: 2, ControlNet: \u0026#34;preprocessor: none, model: control_v1p_sd15_qrcode_monster [a6e58995], weight: 1.35-1.5, starting/ending: (0.05, 1), resize mode: Resize and Fill, pixel perfect: True, control mode: Balanced, preprocessor params: (512, 64, 64)\u0026#34;, Version: v1.3. Step 2: Create the Base QR Code After understanding the key points above, use a QR code generation tool to create a base QR code for SD input. There are many web-based generators available; choose freely. For convenience, here is a useful WebUI plugin:\nAnthony\u0026rsquo;s QR Toolkit: Integrated QR code generation and optimization tool for WebUI https://github.com/antfu/sd-webui-qrcode-toolkit After creating the QR code, click \u0026ldquo;Download\u0026rdquo; to save it locally, or click \u0026ldquo;Send to ControlNet\u0026rdquo; to pass it directly for the next step.\nStep 3: Determine the Art Style The core of creating art with Stable Diffusion is choosing the right model + prompts. Before creating artistic QR codes, we recommend generating an image without ControlNet first to test the style.\nGeneration parameters:\n1 2 3 4 5 Prompt: mountain, green grassland, sky, cloud, bird, blue sky, no human, day, wide shot, flying, border, outdoors, white bird, scenery Negative prompt: easynegative Steps: 20, Sampler: Euler a, CFG scale: 7, Seed: 4078355702, Face restoration: CodeFormer, Size: 512x512, Model hash: 876b4c7ba5, Model: cetusMix_Whalefall2, Clip skip: 2, Version: v1.3.2 Step 4: Import QR Code into ControlNet After confirming the image style, upload the unprocessed QR code to ControlNet. Pay attention to these configuration options:\n\u0026ldquo;Enable\u0026rdquo; button: Check to ensure ControlNet is active during generation Model selector: Select control_v1p_sd15_qrcode_monster to strengthen QR code control Control weight: For the qrcode_monster model, we recommend setting it between 1.1–1.6 Guidance start/end timing: Start timing recommended between 0–0.1, end timing recommended at 1 In the txt2img configuration, adjust two key values:\nSampling steps: Recommended 30–50 (the default of 20 is insufficient for generating high-quality QR code images) Width/Height: Match the original QR code aspect ratio from ControlNet After all parameters are configured, click generate. Here we can see a good result — the QR code passes scanning tests on mobile phones.\nIf the generated QR code doesn\u0026rsquo;t meet expectations, try fine-tuning the following parameters and increase the total batch count, iterating to approach the desired result:\nPrompts Sampling method ControlNet control weight ControlNet guidance start/end timing When necessary, use the X/Y/Z Plot in \u0026ldquo;Scripts\u0026rdquo; to compare QR code generation effects under different parameters. Here we compared ControlNet\u0026rsquo;s control weight and guidance start timing:\nEnhancing QR Codes with OpenPose Building on the QR code techniques above, we can take it further by combining OpenPose with QR codes to create even more dynamic and artistic results. OpenPose generates skeleton maps of human poses, which serve as an additional ControlNet input to control character poses in the generated image.\nExample Showcase Here are some example results combining OpenPose pose control with QR code generation:\nThe prompt used for the example above:\n1 2 3 (school girl:1.6, walking), (a car, side view, to left), (residential area, cherry trees) Negative prompt: (worst quality:1.6),(low quality:1.6), (inaccurate limb:1.2),bad composition, inaccurate eyes, easynegative Steps: 50, Sampler: Euler a, CFG scale: 7, Seed: 3408317133, Size: 900x540, Model: cetusMix_Whalefall2 Environment Setup: Enable Multiple ControlNet Units To use OpenPose and QR Code ControlNet simultaneously, you need at least 2 ControlNet Units enabled:\nGo to Settings → ControlNet Set the Multi ControlNet unit count to 2 (or more) Click Apply Settings, then Reload UI Import Skeleton Data and Enable OpenPose Open the OpenPose Editor extension Click Load JSON to import your prepared skeleton pose data Click Send to txt2img to transfer the pose to ControlNet In ControlNet Unit 0, enable ControlNet and select the model control_v11p_sd15_openpose Import QR Code and Configure Generation Switch to ControlNet Unit 1 Upload your QR code image Select the model control_v1p_sd15_qrcode_monster with a Control Weight of 1.7 Set Sampling Steps to 30–50 for better quality Adjust Width/Height to match your desired output resolution Prompts and Generation Set your prompts for the final generation:\nPositive prompt:\n1 (1girl:1.6, side lying sleep, on the garden, sunflowers), wooden floor Negative prompt:\n1 extra hands, extra fingers, extra legs, fewer fingers, (low quality, worst quality:1.4), (bad anatomy), (inaccurate limb:1.2),bad composition, inaccurate eyes, extra digit,fewer digits,(extra arms:1.2), signature, easynegative Results Here is the final generated result combining OpenPose and QR code:\nBy cleverly offsetting the QR code position and applying composition techniques, the viewer\u0026rsquo;s focus is effectively shifted from the QR code to the character itself, creating a more natural and harmonious overall image.\nFine-Tuning Tips To achieve the best results when combining OpenPose with QR codes, consider adjusting:\nPrompts: Experiment with different scene descriptions and character poses Sampling method: Try different samplers (Euler a, DPM++ 2M Karras, etc.) Skeleton structure and position: Adjust the pose skeleton to avoid overlapping with QR code critical areas Control weight: Balance between OpenPose (pose accuracy) and QR code (scannability) weights Guidance start/end timing: Fine-tune when each ControlNet kicks in during the denoising process Appendix: ControlNet QRCode Model Selection To date, QRCode Monster is the model with the highest QR code control success rate and best image fusion effect. It can be downloaded from HuggingFace:\nQRCode Monster - HuggingFace Another option is QR Pattern v2.0, best used with IoC Lab\u0026rsquo;s Brightness model as an auxiliary to improve local contrast. However, based on our testing, this model introduces more interference that may significantly alter the image style. Downloads:\nQR Pattern v2.0 - Civitai IoC Lab ControlNet - HuggingFace References AIGC Stable Diffusion Workshop QR Toolkit by Anthony Fu QRCode Monster - HuggingFace IoC Lab ControlNet - HuggingFace Original post: Art QR Code Generation with ControlNet - AI Painting Solution Based on Stable Diffusion\n","date":"2023-09-01T00:00:00+08:00","image":"/p/art-qr-code-controlnet-stable-diffusion/images/2-girl-with-car.png","permalink":"/p/art-qr-code-controlnet-stable-diffusion/","title":"Art QR Code with ControlNet and Stable Diffusion"}]