📖 Detailed Explanation
The Ambassador Pattern is a proxy pattern for handling the cross-cutting concerns that arise when a service in a microservices architecture communicates with external resources (other services, databases, message queues, and so on). As the name "Ambassador" suggests, it mediates and manages communication with the outside on behalf of the service.
This pattern was first systematized in Microsoft's Cloud Design Patterns in 2005 and became widespread rapidly with the development of Kubernetes and container orchestration. It is a specialized form of the Sidecar Pattern, focused on proxy functionality. It runs alongside the application container and intercepts and handles all outbound traffic.
The Ambassador's core role is to abstract away networking-related complexity. Retry logic, timeout settings, Circuit Breaker, TLS termination, load balancing, and service discovery can all be applied without changing application code. It is especially useful when adding modern networking features to legacy applications.
In practice, the Ambassador Pattern forms the data plane of Service Meshes such as Istio and Linkerd, which are based on Envoy Proxy. AWS App Mesh and Consul Connect use the same principle. A sidecar proxy is deployed for each service, consistently providing observability and security for service-to-service communication.
Cross-cutting concerns handled by the Ambassador
Retries & timeouts
Automatic retries for transient failures, exponential backoff, and per-request timeout settings. No application code changes needed.
Circuit Breaker
Breaks the circuit after consecutive failures to prevent failure propagation. Attempts gradual recovery in the half-open state.
mTLS (mutual TLS)
Automates encrypted communication between services. Handles certificate issuance, renewal, and validation transparently.
Observability
Distributed tracing, metrics collection, and access logging. Integrates with Jaeger and Prometheus.
💻 Code Example
Kubernetes - Envoy Sidecar Ambassador
# ambassador-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: order-service
spec:
replicas: 3
selector:
matchLabels:
app: order-service
template:
metadata:
labels:
app: order-service
spec:
containers:
# 메인 애플리케이션 컨테이너
- name: order-service
image: myapp/order-service:v1.2
ports:
- containerPort: 8080
env:
- name: PAYMENT_SERVICE_URL
value: "http://localhost:9000" # Ambassador를 통해 접근
- name: INVENTORY_SERVICE_URL
value: "http://localhost:9001"
# Ambassador (Envoy Sidecar)
- name: envoy-ambassador
image: envoyproxy/envoy:v1.28-latest
ports:
- containerPort: 9000 # Payment service proxy
- containerPort: 9001 # Inventory service proxy
- containerPort: 9901 # Envoy admin
volumeMounts:
- name: envoy-config
mountPath: /etc/envoy
args:
- "-c"
- "/etc/envoy/envoy.yaml"
- "--service-cluster"
- "order-service"
volumes:
- name: envoy-config
configMap:
name: envoy-ambassador-config
Envoy Ambassador configuration
# envoy-config.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: envoy-ambassador-config
data:
envoy.yaml: |
static_resources:
listeners:
# Payment Service 프록시
- name: payment_proxy
address:
socket_address:
address: 0.0.0.0
port_value: 9000
filter_chains:
- filters:
- name: envoy.filters.network.http_connection_manager
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
stat_prefix: payment_http
route_config:
name: payment_route
virtual_hosts:
- name: payment_backend
domains: ["*"]
routes:
- match:
prefix: "/"
route:
cluster: payment_cluster
timeout: 5s
retry_policy:
retry_on: "5xx,reset,connect-failure"
num_retries: 3
per_try_timeout: 2s
http_filters:
- name: envoy.filters.http.router
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
clusters:
- name: payment_cluster
connect_timeout: 1s
type: STRICT_DNS
lb_policy: ROUND_ROBIN
load_assignment:
cluster_name: payment_cluster
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: payment-service.default.svc.cluster.local
port_value: 80
# Circuit Breaker 설정
circuit_breakers:
thresholds:
- max_connections: 100
max_pending_requests: 100
max_requests: 100
max_retries: 3
# 헬스 체크
health_checks:
- timeout: 1s
interval: 5s
unhealthy_threshold: 3
healthy_threshold: 2
http_health_check:
path: "/health"
Go - A simple Ambassador implementation
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/http/httputil"
"net/url"
"time"
"sync/atomic"
)
// CircuitBreaker 상태
type CircuitBreaker struct {
failures int32
threshold int32
state int32 // 0: closed, 1: open, 2: half-open
lastFailure time.Time
resetTimeout time.Duration
}
func NewCircuitBreaker(threshold int32, resetTimeout time.Duration) *CircuitBreaker {
return &CircuitBreaker{
threshold: threshold,
resetTimeout: resetTimeout,
}
}
func (cb *CircuitBreaker) AllowRequest() bool {
state := atomic.LoadInt32(&cb.state)
if state == 0 { // closed
return true
}
if state == 1 { // open
if time.Since(cb.lastFailure) > cb.resetTimeout {
atomic.StoreInt32(&cb.state, 2) // half-open
return true
}
return false
}
return true // half-open: 한 번 시도 허용
}
func (cb *CircuitBreaker) RecordSuccess() {
atomic.StoreInt32(&cb.failures, 0)
atomic.StoreInt32(&cb.state, 0) // closed
}
func (cb *CircuitBreaker) RecordFailure() {
failures := atomic.AddInt32(&cb.failures, 1)
cb.lastFailure = time.Now()
if failures >= cb.threshold {
atomic.StoreInt32(&cb.state, 1) // open
log.Printf("🔴 Circuit OPEN: %d consecutive failures", failures)
}
}
// Ambassador Proxy
type Ambassador struct {
target *url.URL
proxy *httputil.ReverseProxy
circuitBreaker *CircuitBreaker
retryCount int
timeout time.Duration
}
func NewAmbassador(targetURL string, retries int, timeout time.Duration) *Ambassador {
target, _ := url.Parse(targetURL)
proxy := httputil.NewSingleHostReverseProxy(target)
// Transport 커스터마이징 (타임아웃, 연결 풀)
proxy.Transport = &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 10,
IdleConnTimeout: 90 * time.Second,
}
return &Ambassador{
target: target,
proxy: proxy,
circuitBreaker: NewCircuitBreaker(5, 30*time.Second),
retryCount: retries,
timeout: timeout,
}
}
func (a *Ambassador) ServeHTTP(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// Circuit Breaker 체크
if !a.circuitBreaker.AllowRequest() {
log.Printf("🚫 Circuit open, rejecting request: %s", r.URL.Path)
http.Error(w, "Service temporarily unavailable", http.StatusServiceUnavailable)
return
}
// 재시도 로직
var lastErr error
for attempt := 0; attempt <= a.retryCount; attempt++ {
if attempt > 0 {
backoff := time.Duration(attempt*attempt) * 100 * time.Millisecond
time.Sleep(backoff)
log.Printf("🔄 Retry attempt %d for %s", attempt, r.URL.Path)
}
// 요청 복제 (재시도를 위해)
reqCopy := r.Clone(r.Context())
// 타임아웃 적용
client := &http.Client{Timeout: a.timeout}
resp, err := client.Do(reqCopy)
if err != nil {
lastErr = err
a.circuitBreaker.RecordFailure()
continue
}
if resp.StatusCode >= 500 {
lastErr = fmt.Errorf("server error: %d", resp.StatusCode)
a.circuitBreaker.RecordFailure()
resp.Body.Close()
continue
}
// 성공
a.circuitBreaker.RecordSuccess()
// 응답 복사
for k, v := range resp.Header {
w.Header()[k] = v
}
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
resp.Body.Close()
log.Printf("✅ %s %s -> %d (%v)", r.Method, r.URL.Path, resp.StatusCode, time.Since(start))
return
}
log.Printf("❌ All retries failed for %s: %v", r.URL.Path, lastErr)
http.Error(w, "Service unavailable after retries", http.StatusBadGateway)
}
func main() {
// 각 외부 서비스에 대한 Ambassador
paymentAmbassador := NewAmbassador(
"http://payment-service:8080",
3, // 3회 재시도
5*time.Second, // 5초 타임아웃
)
inventoryAmbassador := NewAmbassador(
"http://inventory-service:8080",
2,
3*time.Second,
)
// 포트별 프록시
go func() {
log.Println("🚀 Payment Ambassador on :9000")
http.ListenAndServe(":9000", paymentAmbassador)
}()
log.Println("🚀 Inventory Ambassador on :9001")
http.ListenAndServe(":9001", inventoryAmbassador)
}
Istio Service Mesh - Automatic Ambassador injection
# istio-virtual-service.yaml
# Istio가 Envoy sidecar를 자동으로 주입
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: payment-service
spec:
hosts:
- payment-service
http:
- route:
- destination:
host: payment-service
port:
number: 80
timeout: 5s
retries:
attempts: 3
perTryTimeout: 2s
retryOn: "5xx,reset,connect-failure,retriable-4xx"
---
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: payment-service
spec:
host: payment-service
trafficPolicy:
connectionPool:
tcp:
maxConnections: 100
http:
h2UpgradePolicy: UPGRADE
http1MaxPendingRequests: 100
http2MaxRequests: 100
outlierDetection: # Circuit Breaker
consecutive5xxErrors: 5
interval: 10s
baseEjectionTime: 30s
maxEjectionPercent: 50
🗣️ Examples of Practical Conversations
💬 In an architecture design meeting
"We need to add retry logic to a legacy payment service, but modifying the code is hard. If we attach an Envoy sidecar with the Ambassador pattern, we can apply retries, Circuit Breaker, and even mTLS without changing the application. With Istio, it's managed declaratively."
💬 In a technical interview
"The Ambassador pattern is a specialized form of Sidecar that acts as a proxy for external services. The Envoy injected into each Pod in a Service Mesh is a typical example. It separates cross-cutting concerns into the infrastructure layer so developers can focus on business logic."
💬 In an incident response review
"The reason this payment service outage propagated to the order service is that there was no Circuit Breaker. If we add an outlierDetection setting to the Ambassador, it automatically isolates an endpoint after consecutive 5xx errors."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free