# 🚀 AWS X-Ray Tutorial

---

## 1️⃣ What is AWS X-Ray?

* AWS X-Ray is a **distributed tracing service**.
    
* Helps developers **debug and analyze microservices applications** in AWS (EKS, ECS, Lambda, API Gateway, EC2).
    
* Provides **end-to-end visibility** into requests as they travel through multiple services.
    
* Creates a **service map** to show dependencies, bottlenecks, and errors.
    

👉 In a fintech wealth advisory platform with 15+ microservices, X-Ray helps you answer:

* Why is the Payments API slow?
    
* Which microservice caused the transaction failure?
    
* Where are errors propagating in the request chain?
    

---

## 2️⃣ Why Do We Use It?

✅ Detect **latency bottlenecks**.  
✅ Trace **failed transactions** across services.  
✅ Monitor **downstream dependencies** (DB, S3, third-party APIs).  
✅ Improve **observability** in microservices.  
✅ Support compliance (audit logs of request flows).

---

## 3️⃣ Key Concepts

* **Segment** → data recorded about a single request to a service.
    
* **Subsegment** → finer-grained trace of calls inside a segment (e.g., SQL query).
    
* **Trace** → a collection of segments following a single request across services.
    
* **Service Map** → a visual representation of all services and their interactions.
    
* **Annotations** → indexed metadata (e.g., `user_id`) for filtering.
    
* **Sampling** → controls how many requests are traced to reduce cost.
    

---

## 4️⃣ Setup: Step-by-Step

### 🔹 Step 1: Enable X-Ray Daemon (EKS example)

Deploy the X-Ray Daemon as a DaemonSet in your EKS cluster:

```plaintext
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: xray-daemon
  namespace: amazon-cloudwatch
spec:
  selector:
    matchLabels:
      name: xray-daemon
  template:
    metadata:
      labels:
        name: xray-daemon
    spec:
      containers:
        - name: xray-daemon
          image: amazon/aws-xray-daemon
          ports:
            - containerPort: 2000
              protocol: UDP
          resources:
            limits:
              memory: 256Mi
              cpu: 200m
```

Apply:

```plaintext
kubectl apply -f xray-daemon.yaml
```

---

### 🔹 Step 2: Add X-Ray SDK to Your Microservice

For Python (FastAPI/Django):

```plaintext
pip install aws-xray-sdk
```

For Java (Spring Boot):

```plaintext
<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-xray-recorder-sdk-spring</artifactId>
  <version>2.13.0</version>
</dependency>
```

---

### 🔹 Step 3: Instrument Your Code

**Python Example (FastAPI):**

```plaintext
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.ext.fastapi.middleware import XRayMiddleware
from fastapi import FastAPI

app = FastAPI()
app.add_middleware(XRayMiddleware, recorder=xray_recorder)

@app.get("/payments")
def process_payment():
    subsegment = xray_recorder.begin_subsegment("db-query")
    # Simulate DB query
    subsegment.put_annotation("service", "payments")
    xray_recorder.end_subsegment()
    return {"status": "success"}
```

**Java Example (Spring Boot):**

```plaintext
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.xray.entities.Subsegment;

@GetMapping("/transactions")
public String transactions() {
    Subsegment sub = AWSXRay.beginSubsegment("db-call");
    // DB logic
    AWSXRay.endSubsegment();
    return "ok";
}
```

---

### 🔹 Step 4: View in AWS Console

* Go to **AWS X-Ray Console** → Service map.
    
* Filter by `service = payments` or `traceId`.
    
* Drill into errors, latencies, or request paths.
    

---

## 5️⃣ Fintech Use Case (Wealth Advisory App)

* **Payment Service** → detect DB query slowness.
    
* **User Profile Service** → trace delays caused by external credit score API.
    
* **Transactions Service** → trace failures due to RDS connection drops.
    
* **Fraud Detection Service** → track how ML models affect request latency.
    

---

## 6️⃣ CI/CD Integration

* Deploy X-Ray DaemonSet in EKS cluster as part of infra Helm charts.
    
* Use IaC (Terraform/CloudFormation) to enable **X-Ray + CloudWatch Logs**.
    
* Add SDK dependencies at build stage (Maven/pip install).
    
* Run smoke tests to ensure traces appear after deploy.
    

---

## 7️⃣ Advantages

✅ Full **distributed tracing** across microservices.  
✅ Helps with **root cause analysis**.  
✅ Supports **multi-service dependency mapping**.  
✅ Works across **EKS, ECS, Lambda, API Gateway**.  
✅ Low overhead when using **sampling rules**.

---

## 8️⃣ Limitations

❌ Only available in AWS (vendor lock-in).  
❌ Adds small overhead (~5–10ms per trace).  
❌ Requires code instrumentation (extra dev effort).  
❌ Not a replacement for full logging/metrics (needs CloudWatch/Prometheus).

---

## 9️⃣ 🎯 Interview Q&A

**Q1. What is AWS X-Ray? Why do we use it?**  
👉 X-Ray is a distributed tracing system for debugging and analyzing microservices applications. We use it to identify bottlenecks, errors, and latency issues in complex request flows.

**Q2. How is X-Ray different from CloudWatch?**  
👉 CloudWatch provides logs and metrics, while X-Ray gives **distributed request traces** with service maps.

**Q3. How do you instrument a microservice with X-Ray?**  
👉 Install X-Ray SDK, wrap handlers with middleware, deploy the X-Ray Daemon (EKS/Lambda has built-in integration).

**Q4. How do you control costs in X-Ray?**  
👉 Use **sampling rules** to trace only a percentage of requests.

**Q5. Can X-Ray trace external API calls?**  
👉 Yes, via subsegments (e.g., annotate external DB or API latency).

**Q6. How does X-Ray help in a fintech app?**  
👉 Identifies slow APIs (e.g., payments), failed DB calls (transactions), and latency in fraud detection pipelines.

**Q7. What are X-Ray’s limitations?**  
👉 AWS-only, requires code changes, not suitable as a standalone observability solution (needs CloudWatch/Prometheus/ELK).

**Q8. Where in CI/CD would you add X-Ray?**  
👉 In deployment stage — SDK added at build, DaemonSet installed with infra manifests, traces validated in post-deploy checks.

---

✅ That’s the **AWS X-Ray complete tutorial + fintech context + interview prep**.
