<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ed Adelaja on Medium]]></title>
        <description><![CDATA[Stories by Ed Adelaja on Medium]]></description>
        <link>https://medium.com/@edadelaja?source=rss-a38d9bedc097------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*raGNVDppaEYq8G4A</url>
            <title>Stories by Ed Adelaja on Medium</title>
            <link>https://medium.com/@edadelaja?source=rss-a38d9bedc097------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 13:47:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@edadelaja/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Nginx In Modern DevOps]]></title>
            <link>https://medium.com/@edadelaja/nginx-in-modern-devops-f7129930c4f6?source=rss-a38d9bedc097------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7129930c4f6</guid>
            <dc:creator><![CDATA[Ed Adelaja]]></dc:creator>
            <pubDate>Sat, 07 Jun 2025 00:29:52 GMT</pubDate>
            <atom:updated>2025-06-07T00:29:52.867Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W-Aln_TzLpUn084p" /><figcaption>Photo by <a href="https://unsplash.com/@ankitdembla?utm_source=medium&amp;utm_medium=referral">Ankit Dembla</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In our previous discussions about DevOps metrics, continuous delivery, and container orchestration, we’ve explored how modern applications are built, deployed, and monitored. But there’s a crucial piece we haven’t covered yet, and this is how traffic actually reaches your applications and how you ensure they stay constantly performing under load. This is where Nginx comes in.</p><p>Nginx (pronounced “engine-x”) has evolved from a simple web server into the backbone of modern web infrastructure. If you’re building scalable applications, understanding Nginx is essential.</p><h3>What Makes Nginx Special?</h3><p>Unlike traditional web servers that create a new process or thread for each request, Nginx uses an event-driven architecture. I would describe it like a restaurant where instead of assigning one waiter to each table for the entire meal, Nginx is like having efficient staff who can handle multiple tables simultaneously, only spending time where action is needed.</p><p>This design allows a single Nginx instance to handle thousands of simultaneous connections with minimal resource usage and this is perfect for modern applications that need to scale.</p><h3>Nginx as a Reverse Proxy: Your Application’s BodyGuard</h3><p>One of Nginx’s most powerful roles is as a reverse proxy. While a forward proxy sits between clients and the internet, a reverse proxy sits between the internet and your servers.</p><p>Below is a basic reverse proxy configuration:</p><pre>server {<br>    listen 80;<br>    server_name myapp.com;<br>    <br>    location / {<br>        proxy_pass http://localhost:3000;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>    }<br>}</pre><p>The configuration above does something powerful. It takes all requests coming to your domain and forwards them to your application running on port 3000. But why not just run your app directly on port 80?</p><p>The reverse proxy provides several benefits namely: it handles SSL termination, adds security headers, enables caching, and most importantly, it allows you to run multiple applications behind a single entry point. Your Node.js app can focus on business logic while Nginx handles the web server responsibilities.</p><h3>Load Balancing: Distributing The Load</h3><p>As your application grows, you’ll need multiple instances. Nginx’s load balancing smoothens this for you:</p><pre>upstream app_servers {<br>    server 127.0.0.1:3001;<br>    server 127.0.0.1:3002;<br>    server 127.0.0.1:3003;<br>    <br>    # Health checks<br>    server 127.0.0.1:3004 backup;<br>}<br><br>server {<br>    listen 80;<br>    server_name myapp.com;<br>    <br>    location / {<br>        proxy_pass http://app_servers;<br>    }<br>}</pre><p>This configuration automatically distributes requests across three different application instances. So if one server goes down, Nginx detects it and routes traffic to the healthy servers. The backup server only receives traffic if all the primary servers fail.</p><p>You can also implement different load balancing strategies:</p><pre>upstream app_servers {<br>    least_conn;  # Route to server with fewest active connections<br>    # ip_hash;   # Stick sessions to specific servers<br>    # random;    # Random distribution<br>    <br>    server 127.0.0.1:3001 weight=3;<br>    server 127.0.0.1:3002 weight=1;<br>}</pre><h3>Caching: For Performance Improvement</h3><p>Nginx’s caching capabilities can improve your application’s performance:</p><pre># Define cache path and settings<br>proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=app_cache:10m max_size=1g inactive=60m;<br><br>server {<br>    listen 80;<br>    server_name myapp.com;<br>    <br>    location /api/ {<br>        proxy_cache app_cache;<br>        proxy_cache_valid 200 302 10m;<br>        proxy_cache_valid 404 1m;<br>        <br>        # Add cache status header for debugging<br>        add_header X-Cache-Status $upstream_cache_status;<br>        <br>        proxy_pass http://app_servers;<br>    }<br>    <br>    location /static/ {<br>        # Cache static files for 1 year<br>        expires 1y;<br>        add_header Cache-Control &quot;public, immutable&quot;;<br>        root /var/www;<br>    }<br>}</pre><p>This setup caches(or stores) API responses for 10 minutes and static files for a year. The X-Cache-Status header present there helps you debug whether responses are being served from cache (HIT) or from your application (MISS).</p><p>Container Integration</p><p>In container environments , Nginx could function as an ingress controller. Below is a Docker Compose example:</p><pre>version: &#39;3.8&#39;<br>services:<br>  nginx:<br>    image: nginx:alpine<br>    ports:<br>      - &quot;80:80&quot;<br>    volumes:<br>      - ./nginx.conf:/etc/nginx/nginx.conf<br>    depends_on:<br>      - app1<br>      - app2<br>  <br>  app1:<br>    image: myapp:latest<br>    environment:<br>      - PORT=3000<br>  <br>  app2:<br>    image: myapp:latest<br>    environment:<br>      - PORT=3000</pre><h3>Security and SSL</h3><p>Nginx excels at handling SSL/TLS termination and adding security headers. It does this by default:</p><pre>server {<br>    listen 443 ssl http2;<br>    server_name myapp.com;<br>    <br>    ssl_certificate /path/to/cert.pem;<br>    ssl_certificate_key /path/to/key.pem;<br>    <br>    # Security headers<br>    add_header X-Frame-Options DENY;<br>    add_header X-Content-Type-Options nosniff;<br>    add_header X-XSS-Protection &quot;1; mode=block&quot;;<br>    add_header Strict-Transport-Security &quot;max-age=31536000&quot;;<br>    <br>    location / {<br>        proxy_pass http://app_servers;<br>    }<br>}<br><br># Redirect HTTP to HTTPS<br>server {<br>    listen 80;<br>    server_name myapp.com;<br>    return 301 https://$server_name$request_uri;<br>}</pre><h3>Infrastructure as Code</h3><p>Just like your application code, Nginx configurations should be version-controlled and deployable. Here’s how you might template an Nginx config for different environments:</p><pre># nginx.conf.template<br>upstream app_servers {<br>    {{#each app_instances}}<br>    server {{host}}:{{port}};<br>    {{/each}}<br>}<br><br>server {<br>    listen 80;<br>    server_name {{domain}};<br>    <br>    location / {<br>        proxy_pass http://app_servers;<br>        proxy_set_header Host $host;<br>    }<br>}</pre><p>This template can be added with environment-specific values during deployment, ensuring consistency across development, staging, and production.</p><h3>Monitoring and Nginx</h3><p>Previosuly we’ve discussed at length about monitoring. Nginx provides excellent metrics through its stub_status module:</p><pre>server {<br>    listen 8080;<br>    server_name localhost;<br>    <br>    location /nginx_status {<br>        stub_status on;<br>        access_log off;<br>        allow 127.0.0.1;<br>        deny all;<br>    }<br>}</pre><p>This endpoint provides metrics like active connections, requests per second, and connection states. These are all perfect for feeding into your monitoring systems like Prometheus or Grafana.</p><h3>Conclusion</h3><p>Nginx is not just any tool , it’s more often than not the first point of contact between users and your application. Whether you’re handling SSL termination, load balancing, caching, or providing a unified entry point for microservices, Nginx delivers performance and reliability with little complexity.</p><p>The configurations we have managed to cover here provide a good and solid foundation, but the real power of Nginx lies in the fact that it is very flexible. As your infrastructure grows, Nginx grows with you, handling everything from simple reverse proxying to complex traffic routing in enterprise environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7129930c4f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go for DevOps: Building High-Performance Infrastructure Tools]]></title>
            <link>https://medium.com/@edadelaja/go-for-devops-building-high-performance-infrastructure-tools-6562af19ca6d?source=rss-a38d9bedc097------2</link>
            <guid isPermaLink="false">https://medium.com/p/6562af19ca6d</guid>
            <dc:creator><![CDATA[Ed Adelaja]]></dc:creator>
            <pubDate>Fri, 06 Jun 2025 22:35:52 GMT</pubDate>
            <atom:updated>2025-06-06T22:35:52.409Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vj_Dv3rdU1YMwoMN" /><figcaption>Photo by <a href="https://unsplash.com/@erikvandijk?utm_source=medium&amp;utm_medium=referral">Erik van Dijk</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In our previous discussions on DevOps metrics, continuous delivery, container orchestration, infrastructure as code, and monitoring, we’ve either touched on or relied heavily on tools like Kubernetes, Docker, Prometheus, and Terraform. And what do all these tools have in common? They’re built with Go.</p><p>In the world of infrastructural programming, Go is nothing flashy, but in place of that it is rock-solid. It gets the job done reliably , efficiently and on a large scale. When you need to build a tool that handles thousands of simultaneous operations, manages network connections delicately, and is able to deploy as a single binary, Go is your friend.</p><h3>Why Go Dominates DevOps Tooling</h3><p>Go wasn’t designed specifically for DevOps, but it provided solutions to problems that DevOps engineers come across on a daily basis. Fast compilation, excellent concurrency, cross-platform deployability, and minimal dependencies make it perfect for infrastructure tools.</p><p>Docker containers start in a split of a second, Prometheus scrapes metrics from so many services and all at the same time, and Kubernetes is able to handle thousands of pods. All of these aren’t magic , it’s Go’s design philosophy in action.</p><h4>What Makes It Ideal For DevOps?</h4><ul><li><strong>Fast Compilation</strong>: No waiting around for builds during development cycles.</li><li><strong>Static Binaries</strong>: Deploy anywhere without running into problems with dependencies.</li><li><strong>Concurrency</strong>: Handle multiple operations simultaneously without complexity.</li><li><strong>Network Performance</strong>: Built-in HTTP servers and clients that can scale.</li><li><strong>Memory Efficiency</strong>: Lower resource usage and thus , cheaper infrastructure.</li></ul><h3>Building Your First DevOps Tool: Health Check Monitor</h3><p>Let us start with something practical, in this case a health check monitor that validates service availability across your infrastructure.</p><pre>package main<br><br>import (<br>    &quot;encoding/json&quot;<br>    &quot;fmt&quot;<br>    &quot;log&quot;<br>    &quot;net/http&quot;<br>    &quot;sync&quot;<br>    &quot;time&quot;<br>)<br><br>type ServiceHealth struct {<br>    Name         string    `json:&quot;name&quot;`<br>    URL          string    `json:&quot;url&quot;`<br>    Status       string    `json:&quot;status&quot;`<br>    ResponseTime int64     `json:&quot;response_time_ms&quot;`<br>    LastChecked  time.Time `json:&quot;last_checked&quot;`<br>    Error        string    `json:&quot;error,omitempty&quot;`<br>}<br><br>type HealthChecker struct {<br>    services []ServiceHealth<br>    mutex    sync.RWMutex<br>    client   *http.Client<br>}<br><br>func NewHealthChecker() *HealthChecker {<br>    return &amp;HealthChecker{<br>        services: make([]ServiceHealth, 0),<br>        client: &amp;http.Client{<br>            Timeout: 5 * time.Second,<br>        },<br>    }<br>}<br><br>func (hc *HealthChecker) AddService(name, url string) {<br>    hc.mutex.Lock()<br>    defer hc.mutex.Unlock()<br>    <br>    hc.services = append(hc.services, ServiceHealth{<br>        Name: name,<br>        URL:  url,<br>    })<br>}<br><br>func (hc *HealthChecker) CheckService(service *ServiceHealth) {<br>    start := time.Now()<br>    <br>    resp, err := hc.client.Get(service.URL)<br>    if err != nil {<br>        service.Status = &quot;DOWN&quot;<br>        service.Error = err.Error()<br>        service.ResponseTime = time.Since(start).Milliseconds()<br>        service.LastChecked = time.Now()<br>        return<br>    }<br>    defer resp.Body.Close()<br>    <br>    service.ResponseTime = time.Since(start).Milliseconds()<br>    service.LastChecked = time.Now()<br>    service.Error = &quot;&quot;<br>    <br>    if resp.StatusCode &gt;= 200 &amp;&amp; resp.StatusCode &lt; 300 {<br>        service.Status = &quot;UP&quot;<br>    } else {<br>        service.Status = &quot;DEGRADED&quot;<br>        service.Error = fmt.Sprintf(&quot;HTTP %d&quot;, resp.StatusCode)<br>    }<br>}<br><br>func (hc *HealthChecker) CheckAllServices() {<br>    var wg sync.WaitGroup<br>    <br>    hc.mutex.Lock()<br>    services := make([]*ServiceHealth, len(hc.services))<br>    for i := range hc.services {<br>        services[i] = &amp;hc.services[i]<br>    }<br>    hc.mutex.Unlock()<br>    <br>    for _, service := range services {<br>        wg.Add(1)<br>        go func(s *ServiceHealth) {<br>            defer wg.Done()<br>            hc.CheckService(s)<br>        }(service)<br>    }<br>    <br>    wg.Wait()<br>}<br><br>func (hc *HealthChecker) GetStatus() []ServiceHealth {<br>    hc.mutex.RLock()<br>    defer hc.mutex.RUnlock()<br>    <br>    result := make([]ServiceHealth, len(hc.services))<br>    copy(result, hc.services)<br>    return result<br>}<br><br>func (hc *HealthChecker) StartMonitoring(interval time.Duration) {<br>    ticker := time.NewTicker(interval)<br>    go func() {<br>        for range ticker.C {<br>            hc.CheckAllServices()<br>            hc.logStatus()<br>        }<br>    }()<br>}<br><br>func (hc *HealthChecker) logStatus() {<br>    status := hc.GetStatus()<br>    for _, service := range status {<br>        log.Printf(&quot;Service: %s, Status: %s, Response Time: %dms&quot;, <br>                   service.Name, service.Status, service.ResponseTime)<br>    }<br>}<br><br>func main() {<br>    checker := NewHealthChecker()<br>    <br>    // Add services to monitor<br>    checker.AddService(&quot;Web App&quot;, &quot;http://webapp:8080/health&quot;)<br>    checker.AddService(&quot;Database&quot;, &quot;http://db:5432/health&quot;)<br>    checker.AddService(&quot;Redis&quot;, &quot;http://redis:6379/ping&quot;)<br>    checker.AddService(&quot;API Gateway&quot;, &quot;http://gateway:80/health&quot;)<br>    <br>    // Start monitoring every 30 seconds<br>    checker.StartMonitoring(30 * time.Second)<br>    <br>    // HTTP endpoint for status<br>    http.HandleFunc(&quot;/status&quot;, func(w http.ResponseWriter, r *http.Request) {<br>        w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>        status := checker.GetStatus()<br>        json.NewEncoder(w).Encode(status)<br>    })<br>    <br>    log.Println(&quot;Health checker starting on :8081&quot;)<br>    log.Fatal(http.ListenAndServe(&quot;:8081&quot;, nil))<br>}</pre><p>This tool shows Go’s strengths: we’re seeing it run concurrent health checks using goroutines, make use of mutexes for thread-safe operations, and a built-in HTTP server for status reporting. This can be deployed as a single binary anywhere in your infrastructure.</p><h3>Advanced Tool: Kubernetes Resource Monitor</h3><p>Now to build something a bit more advanced , in this case a tool that monitors Kubernetes resources and sends alerts when thresholds are breached.</p><pre>package main<br><br>import (<br>    &quot;context&quot;<br>    &quot;fmt&quot;<br>    &quot;log&quot;<br>    &quot;os&quot;<br>    &quot;path/filepath&quot;<br>    &quot;time&quot;<br><br>    metav1 &quot;k8s.io/apimachinery/pkg/apis/meta/v1&quot;<br>    &quot;k8s.io/client-go/kubernetes&quot;<br>    &quot;k8s.io/client-go/tools/clientcmd&quot;<br>    &quot;k8s.io/client-go/util/homedir&quot;<br>)<br><br>type ResourceMonitor struct {<br>    clientset *kubernetes.Clientset<br>    namespace string<br>}<br><br>type ResourceUsage struct {<br>    PodName           string  `json:&quot;pod_name&quot;`<br>    Namespace         string  `json:&quot;namespace&quot;`<br>    CPUUsage          float64 `json:&quot;cpu_usage_cores&quot;`<br>    MemoryUsage       int64   `json:&quot;memory_usage_bytes&quot;`<br>    CPULimit          float64 `json:&quot;cpu_limit_cores&quot;`<br>    MemoryLimit       int64   `json:&quot;memory_limit_bytes&quot;`<br>    CPUUtilization    float64 `json:&quot;cpu_utilization_percent&quot;`<br>    MemoryUtilization float64 `json:&quot;memory_utilization_percent&quot;`<br>}<br><br>func NewResourceMonitor(namespace string) (*ResourceMonitor, error) {<br>    var kubeconfig string<br>    if home := homedir.HomeDir(); home != &quot;&quot; {<br>        kubeconfig = filepath.Join(home, &quot;.kube&quot;, &quot;config&quot;)<br>    }<br>    <br>    config, err := clientcmd.BuildConfigFromFlags(&quot;&quot;, kubeconfig)<br>    if err != nil {<br>        return nil, fmt.Errorf(&quot;failed to build config: %v&quot;, err)<br>    }<br>    <br>    clientset, err := kubernetes.NewForConfig(config)<br>    if err != nil {<br>        return nil, fmt.Errorf(&quot;failed to create clientset: %v&quot;, err)<br>    }<br>    <br>    return &amp;ResourceMonitor{<br>        clientset: clientset,<br>        namespace: namespace,<br>    }, nil<br>}<br><br>func (rm *ResourceMonitor) GetPodResources() ([]ResourceUsage, error) {<br>    pods, err := rm.clientset.CoreV1().Pods(rm.namespace).List(<br>        context.TODO(), <br>        metav1.ListOptions{},<br>    )<br>    if err != nil {<br>        return nil, fmt.Errorf(&quot;failed to list pods: %v&quot;, err)<br>    }<br>    <br>    var resources []ResourceUsage<br>    <br>    for _, pod := range pods.Items {<br>        if pod.Status.Phase != &quot;Running&quot; {<br>            continue<br>        }<br>        <br>        // Get resource limits and requests<br>        var cpuLimit, memoryLimit float64<br>        var cpuRequest, memoryRequest int64<br>        <br>        for _, container := range pod.Spec.Containers {<br>            if limit := container.Resources.Limits; limit != nil {<br>                if cpu := limit.Cpu(); cpu != nil {<br>                    cpuLimit += float64(cpu.MilliValue()) / 1000<br>                }<br>                if memory := limit.Memory(); memory != nil {<br>                    memoryLimit += memory.Value()<br>                }<br>            }<br>            <br>            if request := container.Resources.Requests; request != nil {<br>                if cpu := request.Cpu(); cpu != nil {<br>                    cpuRequest += cpu.MilliValue()<br>                }<br>                if memory := request.Memory(); memory != nil {<br>                    memoryRequest += memory.Value()<br>                }<br>            }<br>        }<br>        <br>        // In a real implementation, you&#39;d get actual usage from metrics-server<br>        // For demo purposes, we&#39;ll simulate some usage<br>        usage := ResourceUsage{<br>            PodName:           pod.Name,<br>            Namespace:         pod.Namespace,<br>            CPULimit:          cpuLimit,<br>            MemoryLimit:       memoryLimit,<br>            CPUUsage:          float64(cpuRequest) / 1000 * 0.7, // Simulated<br>            MemoryUsage:       memoryRequest * 8 / 10,           // Simulated<br>        }<br>        <br>        if cpuLimit &gt; 0 {<br>            usage.CPUUtilization = (usage.CPUUsage / cpuLimit) * 100<br>        }<br>        if memoryLimit &gt; 0 {<br>            usage.MemoryUtilization = (float64(usage.MemoryUsage) / float64(memoryLimit)) * 100<br>        }<br>        <br>        resources = append(resources, usage)<br>    }<br>    <br>    return resources, nil<br>}<br><br>func (rm *ResourceMonitor) CheckThresholds(resources []ResourceUsage) []string {<br>    var alerts []string<br>    <br>    for _, resource := range resources {<br>        if resource.CPUUtilization &gt; 80 {<br>            alerts = append(alerts, fmt.Sprintf(<br>                &quot;HIGH CPU: Pod %s in namespace %s is using %.1f%% CPU&quot;,<br>                resource.PodName, resource.Namespace, resource.CPUUtilization,<br>            ))<br>        }<br>        <br>        if resource.MemoryUtilization &gt; 85 {<br>            alerts = append(alerts, fmt.Sprintf(<br>                &quot;HIGH MEMORY: Pod %s in namespace %s is using %.1f%% memory&quot;,<br>                resource.PodName, resource.Namespace, resource.MemoryUtilization,<br>            ))<br>        }<br>    }<br>    <br>    return alerts<br>}<br><br>func (rm *ResourceMonitor) SendAlert(message string) {<br>    // In production, integrate with Slack, PagerDuty, etc.<br>    log.Printf(&quot;ALERT: %s&quot;, message)<br>    <br>    // Example webhook notification<br>    // payload := map[string]string{&quot;text&quot;: message}<br>    // jsonData, _ := json.Marshal(payload)<br>    // http.Post(&quot;https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK&quot;, <br>    //           &quot;application/json&quot;, bytes.NewBuffer(jsonData))<br>}<br><br>func (rm *ResourceMonitor) StartMonitoring() {<br>    ticker := time.NewTicker(60 * time.Second)<br>    defer ticker.Stop()<br>    <br>    for {<br>        select {<br>        case &lt;-ticker.C:<br>            resources, err := rm.GetPodResources()<br>            if err != nil {<br>                log.Printf(&quot;Error getting resources: %v&quot;, err)<br>                continue<br>            }<br>            <br>            alerts := rm.CheckThresholds(resources)<br>            for _, alert := range alerts {<br>                rm.SendAlert(alert)<br>            }<br>            <br>            log.Printf(&quot;Monitored %d pods, generated %d alerts&quot;, <br>                      len(resources), len(alerts))<br>        }<br>    }<br>}<br><br>func main() {<br>    namespace := os.Getenv(&quot;MONITOR_NAMESPACE&quot;)<br>    if namespace == &quot;&quot; {<br>        namespace = &quot;default&quot;<br>    }<br>    <br>    monitor, err := NewResourceMonitor(namespace)<br>    if err != nil {<br>        log.Fatalf(&quot;Failed to create monitor: %v&quot;, err)<br>    }<br>    <br>    log.Printf(&quot;Starting Kubernetes resource monitor for namespace: %s&quot;, namespace)<br>    monitor.StartMonitoring()<br>}</pre><h3>Deployment Automation: Build and Release Tool</h3><p>Real-world DevOps often requires custom deployment workflows. Here’s a tool that builds, tests, and deploys applications:</p><pre>package main<br><br>import (<br>    &quot;bufio&quot;<br>    &quot;fmt&quot;<br>    &quot;log&quot;<br>    &quot;os&quot;<br>    &quot;os/exec&quot;<br>    &quot;strings&quot;<br>    &quot;time&quot;<br>)<br><br>type DeploymentPipeline struct {<br>    AppName     string<br>    GitRepo     string<br>    DockerImage string<br>    Environment string<br>}<br><br>func (dp *DeploymentPipeline) RunCommand(name string, args ...string) error {<br>    log.Printf(&quot;Running: %s %s&quot;, name, strings.Join(args, &quot; &quot;))<br>    <br>    cmd := exec.Command(name, args...)<br>    cmd.Stdout = os.Stdout<br>    cmd.Stderr = os.Stderr<br>    <br>    return cmd.Run()<br>}<br><br>func (dp *DeploymentPipeline) RunCommandWithOutput(name string, args ...string) (string, error) {<br>    cmd := exec.Command(name, args...)<br>    output, err := cmd.CombinedOutput()<br>    return string(output), err<br>}<br><br>func (dp *DeploymentPipeline) GitOperations() error {<br>    log.Println(&quot;=== Git Operations ===&quot;)<br>    <br>    // Pull latest changes<br>    if err := dp.RunCommand(&quot;git&quot;, &quot;pull&quot;, &quot;origin&quot;, &quot;main&quot;); err != nil {<br>        return fmt.Errorf(&quot;git pull failed: %v&quot;, err)<br>    }<br>    <br>    // Get current commit hash<br>    hash, err := dp.RunCommandWithOutput(&quot;git&quot;, &quot;rev-parse&quot;, &quot;--short&quot;, &quot;HEAD&quot;)<br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to get commit hash: %v&quot;, err)<br>    }<br>    <br>    dp.DockerImage = fmt.Sprintf(&quot;%s:%s&quot;, dp.AppName, strings.TrimSpace(hash))<br>    log.Printf(&quot;Using image tag: %s&quot;, dp.DockerImage)<br>    <br>    return nil<br>}<br><br>func (dp *DeploymentPipeline) RunTests() error {<br>    log.Println(&quot;=== Running Tests ===&quot;)<br>    <br>    // Run unit tests<br>    if err := dp.RunCommand(&quot;go&quot;, &quot;test&quot;, &quot;./...&quot;); err != nil {<br>        return fmt.Errorf(&quot;unit tests failed: %v&quot;, err)<br>    }<br>    <br>    // Run integration tests if they exist<br>    if _, err := os.Stat(&quot;integration-tests&quot;); err == nil {<br>        if err := dp.RunCommand(&quot;go&quot;, &quot;test&quot;, &quot;./integration-tests/...&quot;); err != nil {<br>            return fmt.Errorf(&quot;integration tests failed: %v&quot;, err)<br>        }<br>    }<br>    <br>    log.Println(&quot;All tests passed!&quot;)<br>    return nil<br>}<br><br>func (dp *DeploymentPipeline) BuildImage() error {<br>    log.Println(&quot;=== Building Docker Image ===&quot;)<br>    <br>    return dp.RunCommand(&quot;docker&quot;, &quot;build&quot;, &quot;-t&quot;, dp.DockerImage, &quot;.&quot;)<br>}<br><br>func (dp *DeploymentPipeline) PushImage() error {<br>    log.Println(&quot;=== Pushing Docker Image ===&quot;)<br>    <br>    if err := dp.RunCommand(&quot;docker&quot;, &quot;push&quot;, dp.DockerImage); err != nil {<br>        return fmt.Errorf(&quot;docker push failed: %v&quot;, err)<br>    }<br>    <br>    return nil<br>}<br><br>func (dp *DeploymentPipeline) UpdateKubernetes() error {<br>    log.Println(&quot;=== Updating Kubernetes Deployment ===&quot;)<br>    <br>    // Update deployment image<br>    deploymentName := fmt.Sprintf(&quot;%s-deployment&quot;, dp.AppName)<br>    <br>    if err := dp.RunCommand(&quot;kubectl&quot;, &quot;set&quot;, &quot;image&quot;, <br>        fmt.Sprintf(&quot;deployment/%s&quot;, deploymentName),<br>        fmt.Sprintf(&quot;%s=%s&quot;, dp.AppName, dp.DockerImage),<br>        &quot;-n&quot;, dp.Environment); err != nil {<br>        return fmt.Errorf(&quot;kubectl set image failed: %v&quot;, err)<br>    }<br>    <br>    // Wait for rollout to complete<br>    if err := dp.RunCommand(&quot;kubectl&quot;, &quot;rollout&quot;, &quot;status&quot;, <br>        fmt.Sprintf(&quot;deployment/%s&quot;, deploymentName),<br>        &quot;-n&quot;, dp.Environment,<br>        &quot;--timeout=300s&quot;); err != nil {<br>        return fmt.Errorf(&quot;rollout failed: %v&quot;, err)<br>    }<br>    <br>    log.Println(&quot;Deployment completed successfully!&quot;)<br>    return nil<br>}<br><br>func (dp *DeploymentPipeline) HealthCheck() error {<br>    log.Println(&quot;=== Running Health Check ===&quot;)<br>    <br>    // Get service endpoint<br>    serviceName := fmt.Sprintf(&quot;%s-service&quot;, dp.AppName)<br>    output, err := dp.RunCommandWithOutput(&quot;kubectl&quot;, &quot;get&quot;, &quot;service&quot;, <br>        serviceName, &quot;-n&quot;, dp.Environment, <br>        &quot;-o&quot;, &quot;jsonpath={.status.loadBalancer.ingress[0].ip}&quot;)<br>    <br>    if err != nil {<br>        return fmt.Errorf(&quot;failed to get service IP: %v&quot;, err)<br>    }<br>    <br>    serviceIP := strings.TrimSpace(output)<br>    if serviceIP == &quot;&quot; {<br>        log.Println(&quot;Service IP not ready, skipping health check&quot;)<br>        return nil<br>    }<br>    <br>    // Simple HTTP health check<br>    healthURL := fmt.Sprintf(&quot;http://%s/health&quot;, serviceIP)<br>    log.Printf(&quot;Checking health at: %s&quot;, healthURL)<br>    <br>    // In a real implementation, you&#39;d make HTTP requests here<br>    log.Println(&quot;Health check passed!&quot;)<br>    <br>    return nil<br>}<br><br>func (dp *DeploymentPipeline) Run() error {<br>    startTime := time.Now()<br>    <br>    log.Printf(&quot;Starting deployment pipeline for %s to %s&quot;, dp.AppName, dp.Environment)<br>    <br>    steps := []struct {<br>        name string<br>        fn   func() error<br>    }{<br>        {&quot;Git Operations&quot;, dp.GitOperations},<br>        {&quot;Run Tests&quot;, dp.RunTests},<br>        {&quot;Build Image&quot;, dp.BuildImage},<br>        {&quot;Push Image&quot;, dp.PushImage},<br>        {&quot;Update Kubernetes&quot;, dp.UpdateKubernetes},<br>        {&quot;Health Check&quot;, dp.HealthCheck},<br>    }<br>    <br>    for _, step := range steps {<br>        log.Printf(&quot;Starting step: %s&quot;, step.name)<br>        if err := step.fn(); err != nil {<br>            return fmt.Errorf(&quot;step &#39;%s&#39; failed: %v&quot;, step.name, err)<br>        }<br>    }<br>    <br>    duration := time.Since(startTime)<br>    log.Printf(&quot;Deployment completed successfully in %v&quot;, duration)<br>    <br>    return nil<br>}<br><br>func main() {<br>    if len(os.Args) &lt; 3 {<br>        log.Fatal(&quot;Usage: deployer &lt;app-name&gt; &lt;environment&gt;&quot;)<br>    }<br>    <br>    pipeline := &amp;DeploymentPipeline{<br>        AppName:     os.Args[1],<br>        Environment: os.Args[2],<br>    }<br>    <br>    if err := pipeline.Run(); err != nil {<br>        log.Fatalf(&quot;Deployment failed: %v&quot;, err)<br>    }<br>}</pre><h3>Integrations with Existing DevOps Tools</h3><p>Go’s ecosystem allows for a smooth integration with your existing DevOps stack:</p><h4>Prometheus Metrics Export:</h4><pre>import (<br>    &quot;github.com/prometheus/client_golang/prometheus&quot;<br>    &quot;github.com/prometheus/client_golang/prometheus/promhttp&quot;<br>)<br><br>var (<br>    deploymentCounter = prometheus.NewCounterVec(<br>        prometheus.CounterOpts{<br>            Name: &quot;deployments_total&quot;,<br>            Help: &quot;Total number of deployments&quot;,<br>        },<br>        []string{&quot;app&quot;, &quot;environment&quot;, &quot;status&quot;},<br>    )<br>)<br><br>func init() {<br>    prometheus.MustRegister(deploymentCounter)<br>}<br><br>// In your deployment function<br>deploymentCounter.WithLabelValues(appName, environment, &quot;success&quot;).Inc()</pre><h4>Docker Integration:</h4><pre>import &quot;github.com/docker/docker/client&quot;<br><br>func buildAndPushImage(imageName string) error {<br>    cli, err := client.NewClientWithOpts(client.FromEnv)<br>    if err != nil {<br>        return err<br>    }<br>    <br>    // Build and push operations using Docker API<br>    // More programmatic control than shell commands<br>}</pre><h3>Best Practices for Performance and Deployment</h3><h4><strong>Optimization Techniques:</strong></h4><ul><li>Use connection pooling for database and HTTP clients.</li><li>Implement graceful shutdown with context cancellation.</li><li>Profile your applications with Go’s built-in pprof.</li><li>Use worker pools for concurrent operations.</li></ul><h4>Deployment Strategies:</h4><pre>// Multi-stage Dockerfile for Go applications<br>FROM golang:1.21-alpine AS builder<br>WORKDIR /app<br>COPY go.mod go.sum ./<br>RUN go mod download<br>COPY . .<br>RUN CGO_ENABLED=0 GOOS=linux go build -o main .<br><br>FROM alpine:latest<br>RUN apk --no-cache add ca-certificates<br>WORKDIR /root/<br>COPY --from=builder /app/main .<br>CMD [&quot;./main&quot;]</pre><h4>Configuration Management:</h4><pre>import &quot;github.com/spf13/viper&quot;<br><br>func loadConfig() {<br>    viper.SetConfigName(&quot;config&quot;)<br>    viper.SetConfigType(&quot;yaml&quot;)<br>    viper.AddConfigPath(&quot;.&quot;)<br>    viper.AutomaticEnv()<br>    <br>    if err := viper.ReadInConfig(); err != nil {<br>        log.Fatalf(&quot;Error reading config file: %v&quot;, err)<br>    }<br>}</pre><h3>Go in your DevOps Workflow</h3><p>Start incorporating Go into your DevOps practice gradually:</p><p><strong>Week 1–2</strong>: Replace simple shell scripts with Go programs for better error handling and testing.</p><p><strong>Week 3–4</strong>: Build custom monitoring tools that integrate with your existing observability stack.</p><p><strong>Month 2</strong>: Develop deployment automation tools tailored to your specific infrastructure needs.</p><p><strong>Month 3+</strong>: Contribute to open-source DevOps tools or build internal platforms.</p><p>The mission here isn’t to replace <strong><em>EVERY</em></strong> tool with Go, it is to have the ability to build exactly what you need when other existing tools fall short. Go gives you the power and the ability to create infrastructure tools that are fast, reliable, and maintainable.</p><p>When your team requires a custom solution , for example a specialized monitoring exporter, a deployment orchestrator, or an integration between disparate systems , Go provides the foundation to build it and get it right the first time.</p><p>In practice, the best DevOps tool is the one that gets the job done most efficiently for your specific problem. Sometimes this is an existing tool and some other times it’s a tool you build yourself. Go ensures that you’re never limited by what’s available to you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6562af19ca6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring and Alerting: Building Systems That Tell You What’s Wrong Before Your Users Do.]]></title>
            <link>https://medium.com/@edadelaja/monitoring-and-alerting-building-systems-that-tell-you-whats-wrong-before-your-users-do-0ed434ba58d0?source=rss-a38d9bedc097------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ed434ba58d0</guid>
            <dc:creator><![CDATA[Ed Adelaja]]></dc:creator>
            <pubDate>Fri, 30 May 2025 22:12:46 GMT</pubDate>
            <atom:updated>2025-05-31T10:20:08.577Z</atom:updated>
            <content:encoded><![CDATA[<p>We have previously discussed on DevOps metrics , continuous delivery and container orchestration. Here, I would like to discuss a critical practice that keeps everything running smoothly: monitoring and alerting.</p><p>I liken it to driving a car with no dashboard, and no dashboard means no fuel gauge, no speedometer and all the other gauges. You know you’re moving forward , but you have no idea exactly how fast you’re going or how much fuel you have left to continue. This is how running applications without proper monitoring in place feels like.</p><h3>The Difference Between Monitoring and Observability</h3><p><strong><em>Monitoring</em></strong> answers the question “Is my system working?” It tracks predefined metrics and alerts when thresholds are breached.</p><p><strong><em>Observability</em></strong> answers the question “Why isn’t my system working?” and it provides the ability to understand the system behavior from external outputs.</p><p>So in line with our dashboard example from earlier on , monitoring can be seen as the warning lights on the dashboard that tell you there is something wrong and observability is like having a mechanic who can tell you exactly what is wrong and why.</p><h3>Pillars of Observability</h3><p>Modern systems require three types of data:</p><ol><li><strong>Metrics:</strong> Numerical measurements over time(CPU usage, error rates and response times)</li><li><strong>Logs:</strong> Detailed records of all that happened(error messages , user actions, system events)</li><li><strong>Traces:</strong> The journey of requests through your system (how a user’s click becomes a database query)</li></ol><h3>Setting up Effective Application Monitoring</h3><p>Let’s start with a practical example using Prometheus and Grafana. They are the industry standard for collection and visualization of metrics.</p><h4>Basic Prometheus Configuration</h4><pre># prometheus.yml<br>global:<br>  scrape_interval: 15s<br>  evaluation_interval: 15s<br><br>scrape_configs:<br>  # Monitor Prometheus itself<br>  - job_name: &#39;prometheus&#39;<br>    static_configs:<br>      - targets: [&#39;localhost:9090&#39;]<br>  <br>  # Monitor your web application<br>  - job_name: &#39;webapp&#39;<br>    static_configs:<br>      - targets: [&#39;app1:8080&#39;, &#39;app2:8080&#39;, &#39;app3:8080&#39;]<br>    metrics_path: &#39;/metrics&#39;<br>    scrape_interval: 10s<br>  <br>  # Monitor your database<br>  - job_name: &#39;postgres&#39;<br>    static_configs:<br>      - targets: [&#39;db:9187&#39;]  # postgres_exporter port<br><br># Alerting rules<br>rule_files:<br>  - &quot;alert_rules.yml&quot;<br><br>alertmanager_configs:<br>  - targets:<br>    - alertmanager:9093</pre><h4>Application Metrics in Code</h4><p>Here’s how to instrument a simple web application:</p><pre># Python Flask app with Prometheus metrics<br>from flask import Flask<br>from prometheus_client import Counter, Histogram, generate_latest<br>import time<br><br>app = Flask(__name__)<br><br># Define metrics<br>REQUEST_COUNT = Counter(<br>    &#39;webapp_requests_total&#39;, <br>    &#39;Total webapp requests&#39;, <br>    [&#39;method&#39;, &#39;endpoint&#39;, &#39;status&#39;]<br>)<br><br>REQUEST_DURATION = Histogram(<br>    &#39;webapp_request_duration_seconds&#39;,<br>    &#39;Webapp request duration&#39;,<br>    [&#39;method&#39;, &#39;endpoint&#39;]<br>)<br><br>ERROR_COUNT = Counter(<br>    &#39;webapp_errors_total&#39;,<br>    &#39;Total webapp errors&#39;,<br>    [&#39;type&#39;]<br>)<br><br>@app.before_request<br>def before_request():<br>    request.start_time = time.time()<br><br>@app.after_request<br>def after_request(response):<br>    # Record request metrics<br>    REQUEST_COUNT.labels(<br>        method=request.method,<br>        endpoint=request.endpoint or &#39;unknown&#39;,<br>        status=response.status_code<br>    ).inc()<br>    <br>    # Record request duration<br>    duration = time.time() - request.start_time<br>    REQUEST_DURATION.labels(<br>        method=request.method,<br>        endpoint=request.endpoint or &#39;unknown&#39;<br>    ).observe(duration)<br>    <br>    # Record errors<br>    if response.status_code &gt;= 400:<br>        ERROR_COUNT.labels(type=&#39;http_error&#39;).inc()<br>    <br>    return response<br><br>@app.route(&#39;/api/users&#39;)<br>def get_users():<br>    try:<br>        # Simulate database call<br>        users = database.get_all_users()<br>        return {&#39;users&#39;: users}<br>    except Exception as e:<br>        ERROR_COUNT.labels(type=&#39;database_error&#39;).inc()<br>        return {&#39;error&#39;: &#39;Database unavailable&#39;}, 500<br><br>@app.route(&#39;/metrics&#39;)<br>def metrics():<br>    return generate_latest()<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(host=&#39;0.0.0.0&#39;, port=8080)</pre><h3>Creating Meaningful Alerts (Not Alert Spam)</h3><p>Bad alerting makes people wake up for non-issues. Good alerting gives you information about problems that actually need attention.</p><h4>Alert Rules That Make Sense</h4><pre># alert_rules.yml<br>groups:<br>  - name: webapp_alerts<br>    rules:<br>      # High error rate alert<br>      - alert: HighErrorRate<br>        expr: |<br>          (<br>            rate(webapp_requests_total{status=~&quot;5..&quot;}[5m]) /<br>            rate(webapp_requests_total[5m])<br>          ) &gt; 0.05<br>        for: 2m  # Alert after 2 minutes of high error rate<br>        labels:<br>          severity: critical<br>          team: backend<br>        annotations:<br>          summary: &quot;High error rate detected&quot;<br>          description: &quot;Error rate is {{ $value | humanizePercentage }} for the last 5 minutes&quot;<br>      <br>      # Response time degradation<br>      - alert: SlowResponseTime<br>        expr: |<br>          histogram_quantile(0.95, <br>            rate(webapp_request_duration_seconds_bucket[5m])<br>          ) &gt; 2.0<br>        for: 5m<br>        labels:<br>          severity: warning<br>          team: backend<br>        annotations:<br>          summary: &quot;Response time degraded&quot;<br>          description: &quot;95th percentile response time is {{ $value }}s&quot;<br>      <br>      # Service availability<br>      - alert: ServiceDown<br>        expr: up{job=&quot;webapp&quot;} == 0<br>        for: 1m<br>        labels:<br>          severity: critical<br>          team: oncall<br>        annotations:<br>          summary: &quot;Service {{ $labels.instance }} is down&quot;<br>          description: &quot;{{ $labels.instance }} has been down for more than 1 minute&quot;<br>      <br>      # Disk space alert<br>      - alert: DiskSpaceLow<br>        expr: |<br>          (<br>            node_filesystem_avail_bytes{mountpoint=&quot;/&quot;} /<br>            node_filesystem_size_bytes{mountpoint=&quot;/&quot;}<br>          ) &lt; 0.10<br>        for: 5m<br>        labels:<br>          severity: warning<br>          team: infrastructure<br>        annotations:<br>          summary: &quot;Low disk space on {{ $labels.instance }}&quot;<br>          description: &quot;Disk space is {{ $value | humanizePercentage }} full&quot;</pre><h3>Log Aggregation That Actually Helps</h3><p>Collecting logs is easy but making them useful is the hard part. Below is a structured approach:</p><h4>Structured Logging Example</h4><pre>import logging<br>import json<br>from datetime import datetime<br><br>class StructuredLogger:<br>    def __init__(self, service_name):<br>        self.service_name = service_name<br>        self.logger = logging.getLogger(service_name)<br>        <br>    def log(self, level, message, **kwargs):<br>        log_entry = {<br>            &#39;timestamp&#39;: datetime.utcnow().isoformat(),<br>            &#39;service&#39;: self.service_name,<br>            &#39;level&#39;: level,<br>            &#39;message&#39;: message,<br>            **kwargs<br>        }<br>        <br>        if level == &#39;ERROR&#39;:<br>            self.logger.error(json.dumps(log_entry))<br>        elif level == &#39;WARN&#39;:<br>            self.logger.warning(json.dumps(log_entry))<br>        else:<br>            self.logger.info(json.dumps(log_entry))<br><br># Usage in your application<br>logger = StructuredLogger(&#39;webapp&#39;)<br><br>@app.route(&#39;/api/users/&lt;user_id&gt;&#39;)<br>def get_user(user_id):<br>    logger.log(&#39;INFO&#39;, &#39;User request received&#39;, <br>               user_id=user_id, <br>               request_id=request.headers.get(&#39;X-Request-ID&#39;))<br>    <br>    try:<br>        user = database.get_user(user_id)<br>        logger.log(&#39;INFO&#39;, &#39;User retrieved successfully&#39;, <br>                   user_id=user_id, <br>                   execution_time_ms=request.execution_time)<br>        return user<br>    except UserNotFound:<br>        logger.log(&#39;WARN&#39;, &#39;User not found&#39;, <br>                   user_id=user_id)<br>        return {&#39;error&#39;: &#39;User not found&#39;}, 404<br>    except Exception as e:<br>        logger.log(&#39;ERROR&#39;, &#39;Database error retrieving user&#39;,<br>                   user_id=user_id,<br>                   error=str(e),<br>                   stack_trace=traceback.format_exc())<br>        return {&#39;error&#39;: &#39;Internal server error&#39;}, 500</pre><h4>ELK Stack Configuration</h4><pre># docker-compose.yml for ELK Stack<br>version: &#39;3.8&#39;<br>services:<br>  elasticsearch:<br>    image: docker.elastic.co/elasticsearch/elasticsearch:8.8.0<br>    environment:<br>      - discovery.type=single-node<br>      - xpack.security.enabled=false<br>    ports:<br>      - &quot;9200:9200&quot;<br>    volumes:<br>      - elasticsearch_data:/usr/share/elasticsearch/data<br><br>  logstash:<br>    image: docker.elastic.co/logstash/logstash:8.8.0<br>    ports:<br>      - &quot;5044:5044&quot;<br>    volumes:<br>      - ./logstash.conf:/usr/share/logstash/pipeline/logstash.conf<br>    depends_on:<br>      - elasticsearch<br><br>  kibana:<br>    image: docker.elastic.co/kibana/kibana:8.8.0<br>    ports:<br>      - &quot;5601:5601&quot;<br>    environment:<br>      - ELASTICSEARCH_HOSTS=http://elasticsearch:9200<br>    depends_on:<br>      - elasticsearch<br><br>volumes:<br>  elasticsearch_data:</pre><pre># logstash.conf - Process application logs<br>input {<br>  beats {<br>    port =&gt; 5044<br>  }<br>}<br><br>filter {<br>  if [fields][service] == &quot;webapp&quot; {<br>    json {<br>      source =&gt; &quot;message&quot;<br>    }<br>    <br>    date {<br>      match =&gt; [ &quot;timestamp&quot;, &quot;ISO8601&quot; ]<br>    }<br>    <br>    if [level] == &quot;ERROR&quot; {<br>      mutate {<br>        add_tag =&gt; [ &quot;error&quot; ]<br>      }<br>    }<br>  }<br>}<br><br>output {<br>  elasticsearch {<br>    hosts =&gt; [&quot;elasticsearch:9200&quot;]<br>    index =&gt; &quot;webapp-logs-%{+YYYY.MM.dd}&quot;<br>  }<br>}</pre><h4>Distributed Tracing for Complex Systems</h4><p>When requests span multiple services, traces show the complete picture:</p><pre># Using OpenTelemetry for distributed tracing<br>from opentelemetry import trace<br>from opentelemetry.exporter.jaeger.thrift import JaegerExporter<br>from opentelemetry.sdk.trace import TracerProvider<br>from opentelemetry.sdk.trace.export import BatchSpanProcessor<br><br># Configure tracing<br>trace.set_tracer_provider(TracerProvider())<br>tracer = trace.get_tracer(__name__)<br><br>jaeger_exporter = JaegerExporter(<br>    agent_host_name=&quot;jaeger&quot;,<br>    agent_port=6831,<br>)<br><br>span_processor = BatchSpanProcessor(jaeger_exporter)<br>trace.get_tracer_provider().add_span_processor(span_processor)<br><br>@app.route(&#39;/api/orders&#39;, methods=[&#39;POST&#39;])<br>def create_order():<br>    with tracer.start_as_current_span(&quot;create_order&quot;) as span:<br>        order_data = request.json<br>        span.set_attribute(&quot;order.user_id&quot;, order_data[&#39;user_id&#39;])<br>        span.set_attribute(&quot;order.items_count&quot;, len(order_data[&#39;items&#39;]))<br>        <br>        # Validate user<br>        with tracer.start_as_current_span(&quot;validate_user&quot;):<br>            user = user_service.get_user(order_data[&#39;user_id&#39;])<br>            if not user:<br>                span.set_attribute(&quot;error&quot;, True)<br>                span.set_attribute(&quot;error.message&quot;, &quot;User not found&quot;)<br>                return {&#39;error&#39;: &#39;Invalid user&#39;}, 400<br>        <br>        # Check inventory<br>        with tracer.start_as_current_span(&quot;check_inventory&quot;):<br>            for item in order_data[&#39;items&#39;]:<br>                if not inventory_service.check_availability(item[&#39;sku&#39;]):<br>                    span.set_attribute(&quot;error&quot;, True)<br>                    span.set_attribute(&quot;error.sku&quot;, item[&#39;sku&#39;])<br>                    return {&#39;error&#39;: f&#39;Item {item[&quot;sku&quot;]} unavailable&#39;}, 400<br>        <br>        # Process payment<br>        with tracer.start_as_current_span(&quot;process_payment&quot;) as payment_span:<br>            payment_result = payment_service.charge_card(<br>                user[&#39;payment_method&#39;], <br>                order_data[&#39;total&#39;]<br>            )<br>            payment_span.set_attribute(&quot;payment.amount&quot;, order_data[&#39;total&#39;])<br>            payment_span.set_attribute(&quot;payment.method&quot;, user[&#39;payment_method&#39;][&#39;type&#39;])<br>            <br>            if not payment_result[&#39;success&#39;]:<br>                span.set_attribute(&quot;error&quot;, True)<br>                return {&#39;error&#39;: &#39;Payment failed&#39;}, 400<br>        <br>        # Create order record<br>        with tracer.start_as_current_span(&quot;save_order&quot;):<br>            order = database.create_order(order_data)<br>            span.set_attribute(&quot;order.id&quot;, order[&#39;id&#39;])<br>        <br>        return {&#39;order_id&#39;: order[&#39;id&#39;]}, 201</pre><h3>Creating Dashboards That Matter</h3><p>Here’s an ideal Grafana dashboard configuration:</p><pre>{<br>  &quot;dashboard&quot;: {<br>    &quot;title&quot;: &quot;Web Application Overview&quot;,<br>    &quot;panels&quot;: [<br>      {<br>        &quot;title&quot;: &quot;Request Rate&quot;,<br>        &quot;type&quot;: &quot;graph&quot;,<br>        &quot;targets&quot;: [<br>          {<br>            &quot;expr&quot;: &quot;rate(webapp_requests_total[5m])&quot;,<br>            &quot;legendFormat&quot;: &quot;{{method}} {{endpoint}}&quot;<br>          }<br>        ]<br>      },<br>      {<br>        &quot;title&quot;: &quot;Error Rate&quot;,<br>        &quot;type&quot;: &quot;singlestat&quot;,<br>        &quot;targets&quot;: [<br>          {<br>            &quot;expr&quot;: &quot;rate(webapp_requests_total{status=~&#39;5..&#39;}[5m]) / rate(webapp_requests_total[5m]) * 100&quot;<br>          }<br>        ],<br>        &quot;thresholds&quot;: &quot;5,10&quot;,<br>        &quot;colorBackground&quot;: true<br>      },<br>      {<br>        &quot;title&quot;: &quot;Response Time Percentiles&quot;,<br>        &quot;type&quot;: &quot;graph&quot;,<br>        &quot;targets&quot;: [<br>          {<br>            &quot;expr&quot;: &quot;histogram_quantile(0.50, rate(webapp_request_duration_seconds_bucket[5m]))&quot;,<br>            &quot;legendFormat&quot;: &quot;50th percentile&quot;<br>          },<br>          {<br>            &quot;expr&quot;: &quot;histogram_quantile(0.95, rate(webapp_request_duration_seconds_bucket[5m]))&quot;,<br>            &quot;legendFormat&quot;: &quot;95th percentile&quot;<br>          },<br>          {<br>            &quot;expr&quot;: &quot;histogram_quantile(0.99, rate(webapp_request_duration_seconds_bucket[5m]))&quot;,<br>            &quot;legendFormat&quot;: &quot;99th percentile&quot;<br>          }<br>        ]<br>      }<br>    ]<br>  }<br>}</pre><h3>On-Call Best Practices</h3><p><strong>Runbook Automation:</strong> Document common issues and their solutions.</p><pre>#!/bin/bash<br># restart-webapp.sh - Automated runbook script<br><br>echo &quot;Checking webapp health...&quot;<br>if ! curl -f http://webapp:8080/health; then<br>    echo &quot;Webapp is unhealthy, restarting...&quot;<br>    <br>    # Scale down to 0 replicas<br>    kubectl scale deployment webapp --replicas=0<br>    <br>    # Wait for pods to terminate<br>    sleep 30<br>    <br>    # Scale back up<br>    kubectl scale deployment webapp --replicas=3<br>    <br>    # Wait for new pods to be ready<br>    kubectl wait --for=condition=ready pod -l app=webapp --timeout=300s<br>    <br>    echo &quot;Webapp restarted successfully&quot;<br>    <br>    # Send notification<br>    curl -X POST https://api.slack.com/api/chat.postMessage \<br>         -H &quot;Authorization: Bearer $SLACK_TOKEN&quot; \<br>         -H &quot;Content-Type: application/json&quot; \<br>         -d &quot;{\&quot;channel\&quot;:\&quot;#ops\&quot;,\&quot;text\&quot;:\&quot;Webapp automatically restarted due to health check failure\&quot;}&quot;<br>else<br>    echo &quot;Webapp is healthy&quot;<br>fi</pre><p><strong>Escalation Policies:</strong> Clear chains of responsibilty.</p><pre># PagerDuty escalation policy<br>escalation_policy:<br>  name: &quot;Backend Team&quot;<br>  escalation_rules:<br>    - escalation_delay_in_minutes: 0<br>      targets:<br>        - type: &quot;user&quot;<br>          id: &quot;primary-oncall&quot;<br>    - escalation_delay_in_minutes: 15<br>      targets:<br>        - type: &quot;user&quot;<br>          id: &quot;secondary-oncall&quot;<br>    - escalation_delay_in_minutes: 30<br>      targets:<br>        - type: &quot;user&quot;<br>          id: &quot;team-lead&quot;</pre><h3>Monitoring is a Product, Not a Project</h3><p>Effective monitoring requires ongoing investment and processing. Start with these fundamentals:</p><p><strong>Monitor User Experience</strong>: Response times and error rates matter more than CPU usage.</p><p><strong>Alert on Symptoms, Not Causes</strong>: Alert when users are affected, not when a single server is busy.</p><p><strong>Make Alerts Actionable</strong>: Every alert should have a clear next step.</p><p><strong>Review Regularly</strong>: Regularly review alerts that fire frequently or do not fire at all.</p><p><strong>Document Everything</strong>: If you figured out a complex issue, document it for the next person.</p><p>It is important to note that the goal isn’t perfect monitoring but actionable monitoring. You want to know about problems that affect users, with enough context to fix them as soon as possible. Start simple, measure the things that matter, and then begin building complexity as your understanding deepens.</p><p>Good monitoring transforms your relationship with production systems from a previously reactive to proactive system management. When done right, you’ll know about problems before your users do, and you will have the information needed to fix these problems quickly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ed434ba58d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Infrastructure as Code: Building Reliable Systems By Automation]]></title>
            <link>https://medium.com/@edadelaja/infrastructure-as-code-building-reliable-systems-by-automation-a867b905e02e?source=rss-a38d9bedc097------2</link>
            <guid isPermaLink="false">https://medium.com/p/a867b905e02e</guid>
            <dc:creator><![CDATA[Ed Adelaja]]></dc:creator>
            <pubDate>Fri, 30 May 2025 21:20:14 GMT</pubDate>
            <atom:updated>2025-05-31T10:05:51.617Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ktfvSj9BIEmCGOhb" /><figcaption>Photo by <a href="https://unsplash.com/@daryan?utm_source=medium&amp;utm_medium=referral">Daryan Shamkhali</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In previous discussions about DevOps metrics and continuous delivery pipelines , we have been able to explore effective measurement and deployment of software. There is a foundation that makes modern DevOps possible: Infrastructure as Code (IaC) , and today we are going to be tackling that.</p><p>Think about building a house by walking to the construction site every day and verbally telling the workers what they should do. “Put a door here, move this wall there.” Now imagine doing this for 30 houses across different states. That’s basically what manual infrastructure management looks like in the digital world.</p><h3>What is Infrastructure as Code?</h3><p>Infrastructure as Code treats your networks , servers and cloud resources like software. And so instead of the tedious process of running manual commands, you write code that describes <strong><em>exactly</em></strong> what your infrastructure should look like and this code becomes the source of truth and a reference point for your whole environment.</p><p>In other words , it’s a blueprint for digital infrastructure. So, just as architects don’t build houses from memory, engineers shouldn’t rebuild servers from scattered documentation.</p><h3>Why Manual Infrastructure is a Liability</h3><p>All organizations that scale beyond a few servers face some challenges:</p><ol><li><strong>Configuration Drift:</strong> For example, Server X was configured in April , and Server Y got configured in March. These servers are supposed to be identical but over time they begin to accumulate differences.</li></ol><p><strong>2. Recovery Problems:</strong> When systems fail, recovery depends on someone remembering how things were previously configured.</p><p><strong>3. Onboarding Struggles:</strong> New team members have to spend weeks learning the commands before being able to deploy anything.</p><h3>Getting Started with Terraform</h3><p>Terraform is the most popular IaC tool out there and this is because it works with any cloud provider. Here is an example that creates a web application infrastructure:</p><pre># Configure the AWS provider<br>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.0&quot;<br>    }<br>  }<br>}<br><br>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>}<br><br># Create a VPC (Virtual Private Cloud)<br>resource &quot;aws_vpc&quot; &quot;webapp_vpc&quot; {<br>  cidr_block           = &quot;10.0.0.0/16&quot;<br>  enable_dns_hostnames = true<br>  enable_dns_support   = true<br>  <br>  tags = {<br>    Name = &quot;webapp-vpc&quot;<br>    Environment = &quot;production&quot;<br>  }<br>}<br><br># Create a public subnet<br>resource &quot;aws_subnet&quot; &quot;public_subnet&quot; {<br>  vpc_id                  = aws_vpc.webapp_vpc.id<br>  cidr_block              = &quot;10.0.1.0/24&quot;<br>  availability_zone       = &quot;us-east-1a&quot;<br>  map_public_ip_on_launch = true<br>  <br>  tags = {<br>    Name = &quot;public-subnet&quot;<br>  }<br>}<br><br># Create an internet gateway<br>resource &quot;aws_internet_gateway&quot; &quot;webapp_igw&quot; {<br>  vpc_id = aws_vpc.webapp_vpc.id<br>  <br>  tags = {<br>    Name = &quot;webapp-igw&quot;<br>  }<br>}<br><br># Create a load balancer<br>resource &quot;aws_lb&quot; &quot;webapp_lb&quot; {<br>  name               = &quot;webapp-lb&quot;<br>  internal           = false<br>  load_balancer_type = &quot;application&quot;<br>  subnets            = [aws_subnet.public_subnet.id]<br>  <br>  enable_deletion_protection = false<br>  <br>  tags = {<br>    Environment = &quot;production&quot;<br>  }<br>}<br><br># Launch template for web servers<br>resource &quot;aws_launch_template&quot; &quot;webapp_template&quot; {<br>  name_prefix   = &quot;webapp-&quot;<br>  image_id      = &quot;ami-0c02fb55956c7d316&quot;  # Amazon Linux 2<br>  instance_type = &quot;t3.micro&quot;<br>  <br>  vpc_security_group_ids = [aws_security_group.webapp_sg.id]<br>  <br>  user_data = base64encode(&lt;&lt;-EOF<br>              #!/bin/bash<br>              yum update -y<br>              yum install -y httpd<br>              systemctl start httpd<br>              systemctl enable httpd<br>              echo &quot;&lt;h1&gt;Web Server ${random_id.server.hex}&lt;/h1&gt;&quot; &gt; /var/www/html/index.html<br>              EOF<br>  )<br>}<br><br># Auto Scaling Group<br>resource &quot;aws_autoscaling_group&quot; &quot;webapp_asg&quot; {<br>  name                = &quot;webapp-asg&quot;<br>  vpc_zone_identifier = [aws_subnet.public_subnet.id]<br>  target_group_arns   = [aws_lb_target_group.webapp_tg.arn]<br>  health_check_type   = &quot;ELB&quot;<br>  <br>  min_size         = 2<br>  max_size         = 10<br>  desired_capacity = 3<br>  <br>  launch_template {<br>    id      = aws_launch_template.webapp_template.id<br>    version = &quot;$Latest&quot;<br>  }<br>  <br>  tag {<br>    key                 = &quot;Name&quot;<br>    value               = &quot;webapp-instance&quot;<br>    propagate_at_launch = true<br>  }<br>}</pre><p>The code above creates a complete web application infrastructure with load balancing and auto-scaling. The beauty here is that running terraform apply will build this entire environment consistently, every time , without fail.</p><h3>Configuration Management with Code</h3><p>While Terraform handles the providing of infrastructure, tools like Ansible manage all that happens inside your servers:</p><pre># playbook.yml - Configure web servers<br>---<br>- hosts: webservers<br>  become: yes<br>  tasks:<br>    - name: Install required packages<br>      yum:<br>        name:<br>          - httpd<br>          - git<br>          - nodejs<br>          - npm<br>        state: present<br>    <br>    - name: Start and enable Apache<br>      systemd:<br>        name: httpd<br>        state: started<br>        enabled: yes<br>    <br>    - name: Deploy application code<br>      git:<br>        repo: &#39;https://github.com/company/webapp.git&#39;<br>        dest: /var/www/html<br>        version: &quot;{{ app_version | default(&#39;main&#39;) }}&quot;<br>      notify: restart httpd<br>    <br>    - name: Install Node.js dependencies<br>      npm:<br>        path: /var/www/html<br>        state: present<br>    <br>    - name: Configure firewall<br>      firewalld:<br>        service: http<br>        permanent: yes<br>        state: enabled<br>        immediate: yes<br>  <br>  handlers:<br>    - name: restart httpd<br>      systemd:<br>        name: httpd<br>        state: restarted</pre><h3>Version Control: Infrastructure Changes with confidence</h3><p>Your infrastructure code remains alongside your application code in Git. This allows for:</p><ol><li><strong>Change Reviews:</strong> Every change to the infrastructure has to go through a pull request and peer review.</li><li><strong>Rollback Capacity: </strong>If something breaks, git revert and terraform apply restore the previous state , and you can try again.</li><li><strong>Change History:</strong> You can see exactly when and why infrastructure was changed.</li></ol><p>Example Workflow:</p><pre># Create a feature branch for infrastructure changes<br>git checkout -b add-redis-cache<br><br># Make changes to Terraform files<br># ... edit main.tf to add Redis cluster ...<br><br># Plan the changes (like a dry run)<br>terraform plan -out=tfplan<br><br># Create pull request for review<br>git add . &amp;&amp; git commit -m &quot;Add Redis cache cluster&quot;<br>git push origin add-redis-cache<br><br># After approval, apply changes<br>terraform apply tfplan</pre><h3>Testing Infrastructure Code</h3><p>Infrastructure code should go through tests just as application code does:</p><pre># terraform-test.sh - Basic validation script<br>#!/bin/bash<br><br>echo &quot;Validating Terraform syntax...&quot;<br>terraform validate<br><br>echo &quot;Checking Terraform formatting...&quot;<br>terraform fmt -check<br><br>echo &quot;Running security scan...&quot;<br>tfsec .<br><br>echo &quot;Testing with Terratest...&quot;<br>cd test &amp;&amp; go test -v -timeout 30m</pre><p>Basic Terratest Example:</p><pre>// test/terraform_test.go<br>package test<br><br>import (<br>    &quot;testing&quot;<br>    &quot;github.com/gruntwork-io/terratest/modules/terraform&quot;<br>    &quot;github.com/stretchr/testify/assert&quot;<br>)<br><br>func TestTerraformWebApp(t *testing.T) {<br>    terraformOptions := &amp;terraform.Options{<br>        TerraformDir: &quot;../&quot;,<br>    }<br>    <br>    defer terraform.Destroy(t, terraformOptions)<br>    terraform.InitAndApply(t, terraformOptions)<br>    <br>    // Verify load balancer was created<br>    lbArn := terraform.Output(t, terraformOptions, &quot;load_balancer_arn&quot;)<br>    assert.NotEmpty(t, lbArn)<br>    <br>    // Verify auto scaling group has correct capacity<br>    asgName := terraform.Output(t, terraformOptions, &quot;autoscaling_group_name&quot;)<br>    assert.Contains(t, asgName, &quot;webapp-asg&quot;)<br>}</pre><h3>Common Issues and Solutions</h3><ol><li><strong>State File Management:</strong> A “state file” is a file used by an Infrastructure as Code (IaC) tool, like Terraform, to record information about what has been deployed by the tool. Terraform tracks infrastructure with this state file. This should never be edited manually , always remotely:</li></ol><pre># backend.tf - Remote state storage<br>terraform {<br>  backend &quot;s3&quot; {<br>    bucket = &quot;company-terraform-state&quot;<br>    key    = &quot;webapp/terraform.tfstate&quot;<br>    region = &quot;us-east-1&quot;<br>    <br>    # State locking to prevent concurrent changes<br>    dynamodb_table = &quot;terraform-locks&quot;<br>    encrypt        = true<br>  }<br>}</pre><p>2. <strong>Secrets Management:</strong> Never put passwords in your code:</p><pre># Use AWS Secrets Manager<br>data &quot;aws_secretsmanager_secret_version&quot; &quot;db_password&quot; {<br>  secret_id = &quot;webapp/database/password&quot;<br>}<br><br>resource &quot;aws_db_instance&quot; &quot;webapp_db&quot; {<br>  # ... other configuration ...<br>  password = data.aws_secretsmanager_secret_version.db_password.secret_string<br>}</pre><p>3. <strong>Dependency Management: </strong>When order of resources matter , always use explicit dependencies:</p><pre>resource &quot;aws_security_group&quot; &quot;webapp_sg&quot; {<br>  # ... configuration ...<br>}<br><br>resource &quot;aws_instance&quot; &quot;webapp&quot; {<br>  # ... configuration ...<br>  vpc_security_group_ids = [aws_security_group.webapp_sg.id]<br>  <br>  depends_on = [aws_internet_gateway.webapp_igw]<br>}</pre><h3>Building Confidence Through Automation</h3><p>Infrastructure as Code transforms management of infrastructure from a manual and thus error-prone process into a reliable and consistent system. The benefits are vast:</p><ol><li><strong>Fast Recovery:</strong> Environments can be reconstructed in minutes and not days.</li><li><strong>Consistent Environments:</strong> Development , staging are production are all very identical to each other.</li><li><strong>Reduced Risk: </strong>Changes go through testing and review before reaching production stage.</li><li><strong>Knowledge Sharing</strong>: Infrastructure as Code is a blueprint and thus the infrastructure knowledge is captured <strong>in code.</strong></li><li><strong>Cost Optimization.</strong></li></ol><p>In conclusion, start small with IaC. Convert one simple service to code, see the benefits, then expand gradually. The initial investment in learning and setup pays dividends every time you need to make a change, recover from failure, or bring a new team member up to speed.</p><p>Always remember: configuring infrastructure manually not only wastes time but creates liability that will slow you down for months or years to come. Infrastructure as Code isn’t just an ideal practice , it’s the foundation that makes all other DevOps practices possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a867b905e02e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Container Orchestration: From Development to Enterprise Production]]></title>
            <link>https://medium.com/@edadelaja/container-orchestration-from-development-to-enterprise-production-19563701a223?source=rss-a38d9bedc097------2</link>
            <guid isPermaLink="false">https://medium.com/p/19563701a223</guid>
            <dc:creator><![CDATA[Ed Adelaja]]></dc:creator>
            <pubDate>Tue, 20 May 2025 14:12:08 GMT</pubDate>
            <atom:updated>2025-05-20T14:12:08.558Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4PzsRwiV-OXf-loJ" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In my previous articles, we talked about DevOps metrics and continuous delivery pipelines. Let’s talk about another main aspect of modern software delivery: container orchestration. This technology has changed how applications deploy and are managed but to use it successfully needs knowledge of its technical possibilities as well as operational implications.</p><p>Before we get into the details of how it is implemented, let’s understand what it’s all about.<br>Containers are light-weight, isolated environments that package an application together with its dependencies. Think of containers as homogeneous software shipping containers — whatever the application needs goes along in a consistent package wherever it goes.<br>Container orchestration is the process of automating the management of these containers in large numbers. Where containers are like individual shipping containers, orchestration is the advanced logistics system that coordinates thousands of them, getting them to the correct destinations, in the correct quantities, at the correct time.</p><h3>Choosing the Right Orchestration Platform</h3><p>The market offers several container orchestration platforms, each with their own advantages:</p><h4><strong>1. Kubernetes: The Industry Standard</strong></h4><p>Kubernetes (K8s) dominates enterprise container orchestration for good reason. Its architecture provides unmatched flexibility and resilience through:</p><ul><li><strong>Declarative configuration</strong>: You specify the desired state, and Kubernetes works to maintain it.</li><li><strong>Self-healing capabilities</strong>: Automatic replacement of failed containers.</li><li><strong>Horizontal scaling</strong>: Efficient distribution of load across multiple instances.</li></ul><p><strong>When to choose Kubernetes:</strong></p><ul><li>For large-scale, complex applications.</li><li>When multi-cloud portability is important (cloud portability is basically the ability to move applications and data between cloud environments).</li><li>For organizations with dedicated operations teams.</li></ul><p><strong>Technical Implementation: Basic Kubernetes Deployment</strong></p><pre># Example Kubernetes deployment manifest<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: myapp<br>  labels:<br>    app: myapp<br>spec:<br>  replicas: 3                    # Run three identical copies for redundancy<br>  selector:<br>    matchLabels:<br>      app: myapp<br>  template:<br>    metadata:<br>      labels:<br>        app: myapp<br>    spec:<br>      containers:<br>      - name: myapp<br>        image: myapp:1.7.9       # The container image to deploy<br>        ports:<br>        - containerPort: 8080    # The port the app listens on<br>        resources:<br>          requests:              # Guaranteed resources<br>            memory: &quot;128Mi&quot;<br>            cpu: &quot;100m&quot;<br>          limits:                # Maximum allowed resources<br>            memory: &quot;256Mi&quot;<br>            cpu: &quot;200m&quot;<br>        livenessProbe:           # Check if container is alive<br>          httpGet:<br>            path: /health<br>            port: 8080<br>          initialDelaySeconds: 30<br>          periodSeconds: 10<br>        readinessProbe:          # Check if container is ready for traffic<br>          httpGet:<br>            path: /ready<br>            port: 8080<br>          initialDelaySeconds: 5<br>          periodSeconds: 5</pre><h4><strong>2. Amazon ECS/EKS: Managed Simplicity</strong></h4><p>AWS’s container services provide streamlined orchestration with:</p><ul><li><strong>Integrated AWS service ecosystem</strong>: Native integration with AWS services.</li><li><strong>Reduced operational overhead</strong>: AWS manages the control plane.</li><li><strong>Simplified networking</strong>: Automatic integration with VPC and load balancers.</li></ul><p>When to choose AWS container services:</p><ul><li>For AWS-centric architectures.</li><li>When operational simplicity is prioritized over portability.</li><li>For smaller teams without Kubernetes expertise.</li></ul><p><strong>Technical Implementation: ECS Task Definition</strong></p><pre>{<br>  &quot;family&quot;: &quot;myapp&quot;,<br>  &quot;networkMode&quot;: &quot;awsvpc&quot;,<br>  &quot;executionRoleArn&quot;: &quot;arn:aws:iam::123456789012:role/ecsTaskExecutionRole&quot;,<br>  &quot;containerDefinitions&quot;: [<br>    {<br>      &quot;name&quot;: &quot;myapp&quot;,<br>      &quot;image&quot;: &quot;123456789012.dkr.ecr.us-east-1.amazonaws.com/myapp:latest&quot;,<br>      &quot;essential&quot;: true,<br>      &quot;portMappings&quot;: [<br>        {<br>          &quot;containerPort&quot;: 8080,<br>          &quot;hostPort&quot;: 8080,<br>          &quot;protocol&quot;: &quot;tcp&quot;<br>        }<br>      ],<br>      &quot;environment&quot;: [        // Environment variables passed to container<br>        {<br>          &quot;name&quot;: &quot;DATABASE_URL&quot;,<br>          &quot;value&quot;: &quot;postgresql://user:password@db.example.com:5432/mydb&quot;<br>        },<br>        {<br>          &quot;name&quot;: &quot;CACHE_HOST&quot;,<br>          &quot;value&quot;: &quot;redis.example.com&quot;<br>        }<br>      ],<br>      &quot;logConfiguration&quot;: {   // Send logs to CloudWatch<br>        &quot;logDriver&quot;: &quot;awslogs&quot;,<br>        &quot;options&quot;: {<br>          &quot;awslogs-group&quot;: &quot;/ecs/myapp&quot;,<br>          &quot;awslogs-region&quot;: &quot;us-east-1&quot;,<br>          &quot;awslogs-stream-prefix&quot;: &quot;ecs&quot;<br>        }<br>      }<br>    }<br>  ],<br>  &quot;requiresCompatibilities&quot;: [&quot;FARGATE&quot;],<br>  &quot;cpu&quot;: &quot;256&quot;,               // 0.25 vCPU<br>  &quot;memory&quot;: &quot;512&quot;             // 512 MB RAM<br>}</pre><h4><strong>3. Docker Swarm: Simplified Orchestration</strong></h4><p>Docker Swarm offers a lighter alternative for smaller deployments:</p><ul><li><strong>Shallow learning curve</strong>: Uses familiar Docker commands.</li><li><strong>Integrated with Docker ecosystem</strong>: Native integration with Docker Compose.</li><li><strong>Simplified setup</strong>: Easy configuration and maintenance.</li></ul><p><strong>When to choose Docker Swarm:</strong></p><ul><li>For small to medium applications.</li><li>When simplicity is more important than advanced features.</li><li>For teams already invested in Docker tooling.</li></ul><p>Technical Implementation: Docker Compose for Swarm</p><pre># docker-compose.yml with swarm mode configuration<br>version: &#39;3.8&#39;<br><br>services:<br>  webapp:<br>    image: myapp:latest<br>    deploy:<br>      replicas: 3                      # Run 3 copies<br>      update_config:<br>        parallelism: 1                 # Update one at a time<br>        delay: 10s                     # Wait 10s between updates<br>        order: start-first             # Start new container before stopping old<br>      restart_policy:<br>        condition: on-failure          # Restart if container fails<br>        max_attempts: 3                # Try 3 times<br>      resources:<br>        limits:<br>          cpus: &#39;0.50&#39;                 # Max CPU usage<br>          memory: 50M                  # Max memory usage<br>    ports:<br>      - &quot;80:80&quot;                        # Expose web port<br>    networks:<br>      - webnet<br><br>  redis:<br>    image: redis:alpine<br>    networks:<br>      - webnet<br><br>networks:<br>  webnet:</pre><h3>Advanced Orchestration Techniques</h3><p>Upon selecting a platform , implementing these advanced techniques will help elevate your container environment:</p><h4><strong>1. Resource Optimization:</strong></h4><p>Correct allocation of resources prevents performance issues as well as waste:</p><p><strong>Kubernetes Resource Quotas</strong></p><pre># Example namespace resource quota<br>apiVersion: v1<br>kind: ResourceQuota<br>metadata:<br>  name: team-quota<br>  namespace: development<br>spec:<br>  hard:<br>    requests.cpu: &quot;10&quot;          # Total CPU that can be requested<br>    requests.memory: 20Gi       # Total memory that can be requested<br>    limits.cpu: &quot;20&quot;            # Total CPU limit<br>    limits.memory: 40Gi         # Total memory limit<br>    pods: &quot;20&quot;                  # Maximum number of pods<br>    services: &quot;10&quot;              # Maximum number of services</pre><p><strong>Implementation Tips:</strong></p><ul><li>Start with resource usage metrics from development environments and further detail them based on production monitoring data.</li><li>Implement vertical pod autoscaling to automatically adjust resource requests based on historical usage.</li><li>Utilize tools such as Goldilocks or kube-resource-report to identify misconfigured resources.</li></ul><h4><strong>2. Service Discovery and Configuration</strong></h4><p>Modern applications require dynamic discovery and configuration systems.</p><p><strong>Kubernetes ConfigMap for Application Configuration</strong></p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: app-config<br>data:<br>  # Environment-specific configuration<br>  APP_ENV: &quot;production&quot;<br>  LOG_LEVEL: &quot;info&quot;<br>  FEATURE_FLAGS: |<br>    {<br>      &quot;newCheckout&quot;: true,<br>      &quot;betaFeature&quot;: false<br>    }<br>  # Configuration file stored directly<br>  application.properties: |<br>    server.port=8080<br>    spring.datasource.url=jdbc:postgresql://db:5432/mydb<br>    spring.datasource.username=${DB_USER}<br>    spring.datasource.password=${DB_PASSWORD}</pre><p><strong>Implementation Tips:</strong></p><ul><li>Use sidecars like Consul Agent or Linkerd for advanced service mesh capabilities.</li><li>Implement dynamic configuration with tools like HashiCorp Vault for sensitive values.</li><li>Create separate configurations for different environments, but maintain the same structure.</li></ul><h4><strong>3. Container Security</strong></h4><p>Container security requires a multi-layered approach:</p><p><strong>Kubernetes Network Policy</strong></p><pre># Restrict pod network access<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: api-network-policy<br>  namespace: production<br>spec:<br>  podSelector:<br>    matchLabels:<br>      app: api-service<br>  policyTypes:<br>  - Ingress<br>  - Egress<br>  ingress:<br>  - from:<br>    - podSelector:<br>        matchLabels:<br>          app: frontend         # Only frontend pods can access the API<br>    ports:<br>    - protocol: TCP<br>      port: 8080               # Only allow access to API port<br>  egress:<br>  - to:<br>    - podSelector:<br>        matchLabels:<br>          app: database         # API can only connect to database pods<br>    ports:<br>    - protocol: TCP<br>      port: 5432               # Only allow access to database port</pre><p><strong>Implementation Tips:</strong></p><ul><li>Implement a container image scanning pipeline to detect vulnerabilities before deployment.</li><li>Use admission controllers like OPA Gatekeeper to enforce security policies at deployment time.</li><li>Apply the principle of least privilege with restricted pod security contexts.</li><li>Set up network policies that allow only necessary communication paths.</li></ul><p><strong>4. Observability Strategy</strong></p><p>Effective container monitoring requires specific tooling:</p><p>Prometheus Service Discovery Configuration</p><pre># prometheus.yml configuration<br>scrape_configs:<br>  - job_name: &#39;kubernetes-pods&#39;<br>    kubernetes_sd_configs:<br>      - role: pod<br>    relabel_configs:<br>      - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]<br>        action: keep<br>        regex: true<br>      - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]<br>        action: replace<br>        target_label: __metrics_path__<br>        regex: (.+)<br>      - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]<br>        action: replace<br>        regex: ([^:]+)(?::\d+)?;(\d+)<br>        replacement: $1:$2<br>        target_label: __address__<br>      - action: labelmap<br>        regex: __meta_kubernetes_pod_label_(.+)</pre><p><strong>Implementation Tips:</strong></p><ul><li>Configure distributed tracing with Jaeger or Zipkin to track requests across services.</li><li>Implement structured logging with a centralized aggregation system.</li><li>Deploy a service mesh like Istio for enhanced telemetry and traffic management.</li><li>Create custom dashboards that combine metrics, logs, and traces for holistic visibility.</li></ul><h4><strong>Scaling for Enterprise: Zero to Production</strong></h4><p>Let’s now look at how container orchestration evolves as organizations grow from development to enterprise scale:</p><p><strong>Phase 1: Development Environment (1–5 Services)</strong></p><p>Focus Areas:</p><ul><li>Developer experience and quick iterations.</li><li>Local development compatibility with production.</li><li>Simple deployment flows.</li></ul><p><strong>Technical Implementation: Docker Compose for Local Development</strong></p><pre># docker-compose.yml for local development<br>version: &#39;3.8&#39;<br><br>services:<br>  app:<br>    build: .                                  # Build from local Dockerfile<br>    volumes:<br>      - ./src:/app/src                        # Mount source code for hot reload<br>    ports:<br>      - &quot;3000:3000&quot;<br>    environment:<br>      NODE_ENV: development<br>      DB_HOST: postgres<br>    depends_on:<br>      - postgres<br><br>  postgres:<br>    image: postgres:13<br>    environment:<br>      POSTGRES_PASSWORD: example<br>      POSTGRES_DB: myapp_dev<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data # Persist database between restarts<br><br>volumes:<br>  postgres_data:</pre><p><strong>Phase 2: Small Production Environment (5–20 Services)</strong></p><p>Focus Areas:</p><ul><li>Redundancy and basic scaling.</li><li>CI/CD integration.</li><li>Central monitoring.</li></ul><p><strong>Technical Implementation: Basic Kubernetes Deployment with HPA</strong></p><pre># Horizontal Pod Autoscaler configuration<br>apiVersion: autoscaling/v2<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: myapp-hpa<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: myapp<br>  minReplicas: 2                             # Minimum instances for redundancy<br>  maxReplicas: 10                            # Maximum instances for scaling<br>  metrics:<br>  - type: Resource<br>    resource:<br>      name: cpu<br>      target:<br>        type: Utilization<br>        averageUtilization: 70               # Scale when CPU hits 70%<br>  - type: Resource<br>    resource:<br>      name: memory<br>      target:<br>        type: Utilization<br>        averageUtilization: 80               # Scale when memory hits 80%</pre><p><strong>Phase 3: Enterprise Environment (20+ Services)</strong></p><p>Focus Areas:</p><ul><li>Multi-cluster/multi-region deployment.</li><li>Advanced security policies.</li><li>Sophisticated failover mechanisms.</li></ul><p><strong>Technical Implementation: Multi-Cluster Federation</strong></p><pre># KubeFed configuration for multi-cluster deployment<br>apiVersion: types.kubefed.io/v1beta1<br>kind: FederatedDeployment<br>metadata:<br>  name: myapp<br>  namespace: global<br>spec:<br>  template:                                  # Template for all clusters<br>    metadata:<br>      labels:<br>        app: myapp<br>    spec:<br>      replicas: 3<br>      selector:<br>        matchLabels:<br>          app: myapp<br>      template:<br>        metadata:<br>          labels:<br>            app: myapp<br>        spec:<br>          containers:<br>          - name: myapp<br>            image: myapp:1.7.9<br>  placement:                                 # Which clusters to deploy to<br>    clusters:<br>    - name: cluster-us-east<br>    - name: cluster-us-west<br>    - name: cluster-eu-central<br>  overrides:                                 # Region-specific overrides<br>  - clusterName: cluster-eu-central<br>    clusterOverrides:<br>    - path: &quot;/spec/replicas&quot;<br>      value: 5                               # More replicas in Europe<br>    - path: &quot;/spec/template/spec/containers/0/env&quot;<br>      value:<br>      - name: REGION<br>        value: &quot;eu&quot;</pre><h3><strong>Common Challenges and Solutions</strong></h3><p>As you implement container orchestration, you will come across some challenges:</p><h4><strong>1. State Management</strong></h4><p><strong>Challenge</strong>: Containers last for short periods , but applications often require a persistent state.</p><p><strong>Solution: StatefulSet with Persistent Volume Chains</strong></p><pre>apiVersion: apps/v1<br>kind: StatefulSet<br>metadata:<br>  name: database<br>spec:<br>  serviceName: &quot;database&quot;<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: database<br>  template:<br>    metadata:<br>      labels:<br>        app: database<br>    spec:<br>      containers:<br>      - name: database<br>        image: postgres:13<br>        volumeMounts:<br>        - name: data<br>          mountPath: /var/lib/postgresql/data<br>  volumeClaimTemplates:                      # Create persistent storage for each pod<br>  - metadata:<br>      name: data<br>    spec:<br>      accessModes: [&quot;ReadWriteOnce&quot;]<br>      storageClassName: &quot;standard&quot;<br>      resources:<br>        requests:<br>          storage: 10Gi</pre><p><strong>Implementation Tips:</strong></p><ul><li>Use StatefulSets for workloads requiring stable network identifiers and persistent storage.</li><li>Implement backup solutions specific to container environments.</li><li>Consider managed database services when appropriate to simplify state management.</li></ul><h4>2. Network Complexity</h4><p><strong>Challenge:</strong> Container networking adds abstract layers that could complicate troubleshooting.</p><p><strong>Solution:</strong> <strong>Service Mesh Implementation</strong></p><pre># Istio Virtual Service for traffic management<br>apiVersion: networking.istio.io/v1alpha3<br>kind: VirtualService<br>metadata:<br>  name: myapp-routing<br>spec:<br>  hosts:<br>  - myapp.example.com<br>  gateways:<br>  - external-gateway<br>  http:<br>  - match:<br>    - headers:<br>        x-test-version:         # Header-based routing<br>          exact: &quot;v2&quot;<br>    route:<br>    - destination:<br>        host: myapp-service<br>        subset: v2              # Route to v2 version<br>  - route:                      # Default route<br>    - destination:<br>        host: myapp-service<br>        subset: v1              # Route to v1 version (default)<br>      weight: 90<br>    - destination:<br>        host: myapp-service<br>        subset: v2              # Route 10% of traffic to v2 (canary)<br>      weight: 10</pre><p><strong>Implementation Tips:</strong></p><ul><li>Start with simple network policies before implementing a full service mesh.</li><li>Use CNI plugins suited to your specific requirements (Calico for network policy, Cilium for eBPF capabilities).</li><li>Document network flows between services to aid in troubleshooting.</li></ul><h4>3. Resource Fragmentation</h4><p><strong>Challenge: </strong>Container placement without proper constraints leads to inefficient use of resources.</p><p><strong>Solution: Advanced Pod Scheduling</strong></p><pre># Pod affinity and anti-affinity rules<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: cache-service<br>spec:<br>  # ... other deployment configs<br>  template:<br>    spec:<br>      affinity:<br>        podAntiAffinity:<br>          requiredDuringSchedulingIgnoredDuringExecution:<br>          - labelSelector:                # Ensure cache pods are on different nodes<br>              matchExpressions:<br>              - key: app<br>                operator: In<br>                values:<br>                - cache-service<br>            topologyKey: &quot;kubernetes.io/hostname&quot;<br>        podAffinity:<br>          preferredDuringSchedulingIgnoredDuringExecution:<br>          - weight: 100<br>            podAffinityTerm:<br>              labelSelector:              # Try to place near the API they serve<br>                matchExpressions:<br>                - key: app<br>                  operator: In<br>                  values:<br>                  - api-service<br>              topologyKey: &quot;topology.kubernetes.io/zone&quot;</pre><p><strong>Implementation Tips:</strong></p><ul><li>Use node labels and taints to guide pod placement for specialized workloads.</li><li>Configure resource quotas at the namespace level to prevent resource hogging.</li><li>Implement cluster autoscaling tied to actual resource usage.</li></ul><h3>Conclusion: Container Orchestration as a Competitive Advantage</h3><p>Container orchestration is no longer a purely technical choice — it’s a business strategy for speeding business agility. By adopting the practices in this article, organizations can:</p><ul><li><strong>Accelerate time-to-market</strong> through environment consistency and automatic deployment.</li><li><strong>Enhance reliability</strong> with self-healing infrastructure and graceful scaling.</li><li><strong>Optimize costs</strong> by increasing resource utilization and rightsizing workloads.</li><li><strong>Enhance security</strong> through isolation, least-privilege access, and automated policy enforcement.</li></ul><p>Keep in mind that container orchestration is a journey, not a destination. Begin with the fundamentals, refine your implementationcontinuously, and introduce more sophisticated patterns gradually as your requirements change. Prioritize addressing actual business issues over deploying technology for technology’s sake.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19563701a223" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Continuous Delivery Pipelines: A Technical Guide for DevOps Teams]]></title>
            <link>https://medium.com/@edadelaja/implementing-continuous-delivery-pipelines-a-technical-guide-for-devops-teams-f2bc33355985?source=rss-a38d9bedc097------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2bc33355985</guid>
            <dc:creator><![CDATA[Ed Adelaja]]></dc:creator>
            <pubDate>Tue, 20 May 2025 10:54:29 GMT</pubDate>
            <atom:updated>2025-05-20T10:54:29.000Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CSeP-vBc6J_mYynhxbBPNA.jpeg" /></figure><p>In my last post, we discussed the metrics for DevOps success. Let’s discuss in detail today the technical implementation of one of the most critical elements of DevOps: the continuous delivery pipeline.<br>Consider a continuous delivery pipeline to be an automated assembly line for your code. Just as an assembly line in manufacturing accepts raw material and converts it into finished goods via a set of quality-tested steps, a CD pipeline accepts developers’ machine code and converts it into production-ready software via automated testing and deployment processes.<br>This article will offer step-by-step instruction in building strong, scalable pipelines to the metrics we’ve outlined above, with explanations that are understandable by technical professionals at any level of experience.</p><h3><strong>The Anatomy of a Modern Continuous Delivery Pipeline</strong></h3><p>A well-designed CD pipeline is the secret to DevOps success. It simplifies the journey of the code from commit to production and guarantees quality, consistency, and velocity.<br>Before we dive into technical solutions, let’s ensure we understand what we’re aiming for: an automated system that takes in new code, ensures it functions as expected, packages it, and distributes it to production safely — all with minimal human intervention. This automation circumvents error-prone human processes while providing us with repeatable, consistent results.<br>Let’s dissect its key parts:</p><ol><li><strong>Source Control Integration</strong></li></ol><p>Your pipeline begins with source control (like Git, where developers store and version their code). This isn’t just about storing code — it’s about creating guardrails that prevent problematic code from ever entering your system.<br>Modern pipelines should include:</p><ul><li><strong>Branch protection rules</strong>: View these as safety doors that prevent direct changes to major code branches (e.g., “main”) without authorization. Think of this like having a few people approve major documents before signing off.</li><li><strong>Commit hooks</strong>: These are quality tests that run automatically each time you commit code, catching trivial issues before they ever reach your codebase — such as a pre-send email spell-check.</li><li><strong>Automation of semantic versioning</strong>: This generates consistent version numbers (e.g., v1.2.3) based on the type of changes being made, helping teams understand the impact of each release.</li></ul><p><strong>Technical Implementation:</strong></p><pre># Example GitHub branch protection configuration<br>branches:<br>  main:<br>    protection:<br>      required_pull_request_reviews:<br>        required_approving_review_count: 2      # Requires two people to approve changes<br>      required_status_checks:<br>        strict: true                            # Ensures tests pass on latest code<br>        contexts: [&quot;continuous-integration/jenkins&quot;, &quot;security-scan&quot;]<br>      enforce_admins: true                       # Even administrators must follow these rules</pre><p><strong>2. Continuous Integration(CI)</strong></p><p>The CI stage verifies code updates through automated testing:</p><ul><li><strong>Fast feedback loops</strong>: Tests should run in parallel where it is possible.</li><li><strong>Test pyramids</strong>: Balance unit, integration, and end-to-end tests.</li><li><strong>Caching strategies</strong>: Accelerate builds by caching dependencies.</li></ul><p><strong>Technical Implementation</strong></p><pre># Example Jenkins Pipeline for CI<br>pipeline {<br>    agent any<br>    <br>    stages {<br>        stage(&#39;Build&#39;) {<br>            steps {<br>                sh &#39;mvn clean compile&#39;<br>            }<br>        }<br>        stage(&#39;Unit Test&#39;) {<br>            steps {<br>                sh &#39;mvn test&#39;<br>            }<br>            post {<br>                always {<br>                    junit &#39;**/target/surefire-reports/*.xml&#39;<br>                }<br>            }<br>        }<br>        stage(&#39;Static Analysis&#39;) {<br>            parallel {<br>                stage(&#39;Linting&#39;) {<br>                    steps {<br>                        sh &#39;npm run lint&#39;<br>                    }<br>                }<br>                stage(&#39;Security Scan&#39;) {<br>                    steps {<br>                        sh &#39;owasp-dependency-check&#39;<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><strong>3. Artifact Management</strong></p><p>Properly managed artifacts ensure reproducible deployments:</p><ul><li><strong>Immutable artifacts</strong>: Build once, deploy many times.</li><li><strong>Versioning strategy</strong>: Clear tracking of what’s deployed where.</li><li><strong>Artifact scanning</strong>: Security validation before deployment.</li></ul><p><strong>Technical implementation:</strong></p><pre># Example Docker image tagging and publishing<br>VERSION=$(git describe --tags --always)<br>COMMIT_HASH=$(git rev-parse --short HEAD)<br><br>docker build -t myapp:${VERSION} .<br>docker tag myapp:${VERSION} myapp:latest<br>docker tag myapp:${VERSION} myapp:${COMMIT_HASH}<br><br># Scan before push<br>trivy image myapp:${VERSION} --severity HIGH,CRITICAL<br><br># Push to registry<br>docker push myapp:${VERSION}<br>docker push myapp:latest<br>docker push myapp:${COMMIT_HASH}</pre><p><strong>4. Infrastructure as Code(IaC)</strong></p><p>Pipeline systems now set up infrastructure as well as applications. Server and network installation was once a tedious, error-filled, and inconsistent process. IaC flips that on its head by treating your infrastructure deployment the same way developers treat code — it’s written down, it’s versioned, and it’s automated.</p><p>Think of IaC as having blueprints for all your IT infrastructure that can create exact duplicates automatically whenever needed:</p><ul><li><strong>Environment parity</strong>: Dev environment is configured exactly the same as production, eliminating the “but it worked on my machine” problem.</li><li><strong>Drift detection:</strong> Unwanted alerts when someone makes unauthorized changes to your infrastructure — like being notified when someone re-arranges your neatly ordered desk.</li><li><strong>State management:</strong> Following what your infrastructure is like at any given time and reverting back to a previous version if needed.</li></ul><p><strong>Technical Implementation:</strong></p><pre># Example Terraform configuration for application infrastructure in AWS<br>provider &quot;aws&quot; {<br>  region = &quot;us-west-2&quot;    # Use AWS&#39;s Oregon region<br>}<br><br># Create a cluster (group of servers) to run our application<br>module &quot;ecs_cluster&quot; {<br>  source  = &quot;terraform-aws-modules/ecs/aws&quot;<br>  version = &quot;~&gt; 3.0&quot;<br>  <br>  name = &quot;${var.environment}-cluster&quot;    # Name it based on environment (dev/staging/prod)<br>  <br>  # Use AWS Fargate (serverless container service)<br>  capacity_providers = [&quot;FARGATE&quot;, &quot;FARGATE_SPOT&quot;]<br>  <br>  default_capacity_provider_strategy = [<br>    {<br>      capacity_provider = &quot;FARGATE_SPOT&quot;    # Use cost-effective spot instances<br>      weight            = 1<br>    }<br>  ]<br>}<br><br># Define how our application should run<br>resource &quot;aws_ecs_task_definition&quot; &quot;app&quot; {<br>  family                   = &quot;app-${var.environment}&quot;<br>  network_mode             = &quot;awsvpc&quot;              # Use AWS virtual private cloud<br>  requires_compatibilities = [&quot;FARGATE&quot;]           # Run on serverless infrastructure<br>  cpu                      = 256                   # Allocate CPU resources<br>  memory                   = 512                   # Allocate memory<br>  execution_role_arn       = aws_iam_role.ecs_execution_role.arn<br>  <br>  # Define the container (packaged application)<br>  container_definitions = jsonencode([<br>    {<br>      name      = &quot;app&quot;<br>      image     = &quot;${var.ecr_repository_url}:${var.image_tag}&quot;    # Which version to deploy<br>      essential = true<br>      <br>      # Open network ports<br>      portMappings = [<br>        {<br>          containerPort = 80    # Web traffic port<br>          hostPort      = 80<br>        }<br>      ]<br>      <br>      # Configure logging<br>      logConfiguration = {<br>        logDriver = &quot;awslogs&quot;<br>        options = {<br>          awslogs-group         = &quot;/ecs/app-${var.environment}&quot;<br>          awslogs-region        = &quot;us-west-2&quot;<br>          awslogs-stream-prefix = &quot;ecs&quot;<br>        }<br>      }<br>    }<br>  ])<br>}</pre><p><strong>5. Deployment Strategies</strong></p><p>Safe deployment strategies reduce change failure rates:</p><ul><li><strong>Blue/green deployments</strong>: Maintain two production environments</li><li><strong>Canary releases</strong>: Gradually route traffic to new versions</li><li><strong>Feature flags</strong>: Decouple deployment from release</li></ul><p><strong>Technical Implementation:</strong></p><pre># Example Kubernetes deployment with canary strategy<br>apiVersion: argoproj.io/v1alpha1<br>kind: Rollout<br>metadata:<br>  name: myapp-rollout<br>spec:<br>  replicas: 10<br>  strategy:<br>    canary:<br>      steps:<br>      - setWeight: 20<br>      - pause: {duration: 10m}<br>      - setWeight: 40<br>      - pause: {duration: 10m}<br>      - setWeight: 60<br>      - pause: {duration: 10m}<br>      - setWeight: 80<br>      - pause: {duration: 10m}<br>  revisionHistoryLimit: 2<br>  selector:<br>    matchLabels:<br>      app: myapp<br>  template:<br>    metadata:<br>      labels:<br>        app: myapp<br>    spec:<br>      containers:<br>      - name: myapp<br>        image: myapp:v1<br>        ports:<br>        - name: http<br>          containerPort: 8080<br>          protocol: TCP</pre><p><strong>6. Observability and Feedback Loops</strong></p><p>Complete the cycle with robust monitoring:</p><ul><li><strong>Distributed tracing</strong>: Track requests across services</li><li><strong>Log aggregation</strong>: Centralize logs for analysis</li><li><strong>Performance metrics</strong>: Monitor application health</li><li><strong>Deployment markers</strong>: Track deployments in monitoring tools</li></ul><p><strong>Technical Implementation:</strong></p><pre># Example Prometheus alerting rules<br>groups:<br>- name: deployment<br>  rules:<br>  - alert: DeploymentFailed<br>    expr: kube_deployment_status_replicas_available{deployment=&quot;myapp&quot;} &lt; kube_deployment_status_replicas_desired{deployment=&quot;myapp&quot;}<br>    for: 10m<br>    labels:<br>      severity: critical<br>    annotations:<br>      summary: &quot;Deployment failed for myapp&quot;<br>      description: &quot;Deployment has been in progress for over 10 minutes&quot;<br><br>- name: application<br>  rules:<br>  - alert: HighErrorRate<br>    expr: sum(rate(http_requests_total{status=~&quot;5..&quot;}[5m])) by (service) / sum(rate(http_requests_total[5m])) by (service) &gt; 0.05<br>    for: 5m<br>    labels:<br>      severity: critical<br>    annotations:<br>      summary: &quot;High HTTP error rate&quot;<br>      description: &quot;Service {{ $labels.service }} has error rate above 5%&quot;</pre><h3>Pipeline Optimization Techniques</h3><p>Now that your pipeline is implemented, work on optimization to enhance the metrics we reviewed in my last article:</p><ol><li><strong>Reduce Lead Time with Parallelization</strong></li></ol><p>Divide your pipeline into individual steps that can run in parallel:</p><pre># Example GitHub Actions parallel workflow<br>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br>    strategy:<br>      matrix:<br>        test-group: [unit, integration, e2e]<br>    steps:<br>      - uses: actions/checkout@v3<br>      - name: Run tests<br>        run: ./scripts/run-tests.sh ${{ matrix.test-group }}</pre><p><strong>2. Improve Deployment Frequency with Caching</strong></p><p>Implement smart caching to reduce build times:</p><pre># Example CircleCI configuration with caching<br>version: 2.1<br>jobs:<br>  build:<br>    docker:<br>      - image: cimg/node:16.13<br>    steps:<br>      - checkout<br>      - restore_cache:<br>          keys:<br>            - v1-dependencies-{{ checksum &quot;package-lock.json&quot; }}<br>            - v1-dependencies-<br>      - run: npm ci<br>      - save_cache:<br>          paths:<br>            - node_modules<br>          key: v1-dependencies-{{ checksum &quot;package-lock.json&quot; }}<br>      - run: npm run build</pre><p><strong>3. Decrease Change Failure Rate with Progressive Testing</strong></p><p>Establish a progressive testing strategy that catches failures early:</p><pre># Example testing progression script<br>#!/bin/bash<br>set -e<br><br># Stage 1: Fast unit tests<br>echo &quot;Running unit tests...&quot;<br>npm run test:unit<br><br># Stage 2: Integration tests<br>echo &quot;Running integration tests...&quot;<br>npm run test:integration<br><br># Only run slower tests if we&#39;re on main branch or release branch<br>if [[ &quot;$CI_BRANCH&quot; == &quot;main&quot; || &quot;$CI_BRANCH&quot; == release/* ]]; then<br>  # Stage 3: E2E tests<br>  echo &quot;Running E2E tests...&quot;<br>  npm run test:e2e<br>  <br>  # Stage 4: Performance tests<br>  echo &quot;Running performance tests...&quot;<br>  npm run test:performance<br>fi</pre><p><strong>4. Reduce MTTR with Automated Rollbacks</strong></p><p>Implement automatic rollback on failure detection</p><pre># Example monitoring script that triggers rollback<br>import requests<br>import subprocess<br>import time<br><br>def check_health():<br>    try:<br>        r = requests.get(&#39;https://api.example.com/health&#39;)<br>        return r.status_code == 200 and r.json()[&#39;status&#39;] == &#39;healthy&#39;<br>    except:<br>        return False<br><br># Deploy new version<br>subprocess.run([&quot;kubectl&quot;, &quot;apply&quot;, &quot;-f&quot;, &quot;deployment.yaml&quot;])<br><br># Monitor health for 5 minutes<br>healthy = True<br>for _ in range(30):  # Check every 10 seconds for 5 minutes<br>    time.sleep(10)<br>    if not check_health():<br>        healthy = False<br>        break<br><br># Rollback if unhealthy<br>if not healthy:<br>    print(&quot;Health check failed, rolling back...&quot;)<br>    subprocess.run([&quot;kubectl&quot;, &quot;rollout&quot;, &quot;undo&quot;, &quot;deployment/myapp&quot;])</pre><h3>Real-World Pipeline Architecture</h3><p>Now that we’ve examined the individual components, let’s step back and look at how they all fit together in a comprehensive pipeline. This flowchart illustrates the journey that code takes from a developer’s computer all the way to production:</p><pre>graph TD<br>    A[Developer Commits Code] --&gt; B[Trigger CI Pipeline]<br>    B --&gt; C[Compile &amp; Build]<br>    B --&gt; D[Static Code Analysis]<br>    B --&gt; E[Security Scanning]<br>    C --&gt; F[Unit Tests]<br>    F --&gt; G[Integration Tests]<br>    G --&gt; H[Build Artifact]<br>    H --&gt; I[Store in Registry]<br>    I --&gt; J[Deploy to Dev]<br>    J --&gt; K[Automated Acceptance Tests]<br>    K --&gt; L[Deploy to Staging]<br>    L --&gt; M[Performance Tests]<br>    L --&gt; N[Security Tests]<br>    M --&gt; O[Deploy to Production]<br>    N --&gt; O<br>    O --&gt; P[Canary Deployment]<br>    P --&gt; Q[Progressive Rollout]<br>    Q --&gt; R[Monitor &amp; Verify]<br>    R --&gt; S[Post-Deployment Tests]</pre><p>This flow represents a sophisticated pipeline that many organizations aspire to implement. Each box represents an automated step, with code progressing through increasingly rigorous testing phases before reaching actual users. The path from top to bottom might take minutes or hours to complete, compared to days or weeks with manual processes.</p><p>See how the pipeline gets increasingly conservative as it nears production — adopting canary deployments (testing against a small user percentage) and progressive rollouts (increasing user exposure gradually) to reduce risk.</p><h3>Conclusion: Technical Excellence Drives Metric Success</h3><p>The technical implementation details discussed in this article aren’t just about engineering elegance — they directly impact the business metrics we covered in my previous article:</p><ul><li><strong>Deployment Frequency</strong>: Automated pipelines enable your team to deploy whenever required (even multiple times daily) instead of being limited by manual processes and coordination overhead.</li><li><strong>Lead Time</strong>: Efficient CI/CD processes with parallel testing and smart caching drastically reduce the time between a developer having an idea and that feature reaching customers.</li><li><strong>Mean Time to Recovery</strong>: When something breaks (and it will), automated rollbacks and comprehensive monitoring mean you can detect and fix issues in minutes rather than hours.</li><li><strong>Change Failure Rate</strong>: Progressive testing and cautious deployment strategies mean fewer customers experience problems, increasing satisfaction and reducing support costs.</li></ul><p>By adopting these technical practices, your team can attain elite DevOps performance and see your metrics consistently improve over time. The payoff for investing in pipeline automation is realized through increased speed of delivery, improved quality, and lower operational overhead.</p><p>Keep in mind that the pipeline itself must change. Use the same mantra of continuous improvement on your pipeline that you use on your app code. Regularly monitor pipeline performance, find bottlenecks, and tune your implementation. Even small improvements compound over time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2bc33355985" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Measuring DevOps Success: Key Metrics for Engineering Teams in the Modern Era]]></title>
            <link>https://medium.com/@edadelaja/measuring-devops-success-key-metrics-for-engineering-teams-in-the-modern-era-13b574891283?source=rss-a38d9bedc097------2</link>
            <guid isPermaLink="false">https://medium.com/p/13b574891283</guid>
            <dc:creator><![CDATA[Ed Adelaja]]></dc:creator>
            <pubDate>Wed, 02 Apr 2025 19:58:23 GMT</pubDate>
            <atom:updated>2025-04-02T19:58:23.272Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LW-nZ23rmF4HUG75" /><figcaption>Photo by <a href="https://unsplash.com/@altumcode?utm_source=medium&amp;utm_medium=referral">AltumCode</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In DevOps, the old adage “you can’t improve what you don’t measure” rings truer than ever. As companies implement DevOps practices to accelerate delivery and improve quality, they often find themselves struggling with a simple question: How do I know if my DevOps transformation is actually succeeding?<br>This article explores the most important metrics that engineering teams can utilize to measure their DevOps success and drive continuous improvement.<br><strong>Beyond Deployment Frequency:</strong> A Holistic Measurement Approach<br>Most teams focus only on how often they deploy code, but actually, good DevOps practices require a more comprehensive measurement system. The DORA (DevOps Research and Assessment) metrics provide a great starting point:<br><em>1. Deployment Frequency</em><br><strong>What it measures</strong>: How often you successfully release to production<br><strong>Why it matters</strong>: More frequent deployment indicates a team’s ability to deploy small batches of changes, reducing risk and accelerating value delivery.<br><strong>Target for high performers</strong>: On-demand deployment (multiple times a day)<br><strong>How to achieve:</strong></p><ul><li>Break work into tiny pieces.</li><li>Automate testing and deployment.</li><li>Employ feature flags to separate deployment from release.</li></ul><p><em>2. Lead Time for Changes</em><br><strong>What it measures:</strong> How long it takes for code to progress from commit to running successfully in production<br><strong>Why it is important:</strong> Lower lead times enable your company to respond quicker to market changes and customer needs.</p><p><strong>Goal for top performers:</strong> Less than one day<br><strong>How to get better:</strong></p><ul><li>Eliminate bottlenecks of approvals.</li><li>Streamline manual stages in your pipeline.</li><li>Pay technical debt that inhibits integration.</li></ul><p><em>3. Mean Time to Recovery (MTTR)</em><br><strong>What it tracks:</strong> How quickly you restore from production errors<br><strong>Why it matters:</strong> Failures will happen; what distinguishes high-performing teams is how quickly they can detect and resolve issues.<br><strong>Target for high performers:</strong> Less than one hour<br><strong>How to improve:</strong></p><ul><li>Employ robust monitoring and alerting.</li><li>Implement standardized incident response procedures.</li><li>Perform chaos engineering to build resilience.</li></ul><p><em>4. Change Failure Rate</em><br><strong>What it measures:</strong> Percentage of changes that result in degraded service or require remediation<br><strong>Why it matters:</strong> Lower failure rates indicate higher quality and more reliable delivery processes.<br><strong>Target for high performers:</strong> 0–15%<br><strong>How to improve:</strong></p><ul><li>Implement rigorous automated testing.</li><li>Use canary deployments or blue/green strategies.</li><li>Conduct thorough post-mortem analyses.</li></ul><p><strong>Beyond DORA: Additional DevOps Metrics to Consider</strong><br>While the DORA metrics are a great foundation, other metrics can provide good insights into your DevOps performance:<br><strong>Infrastructure and Operations Metrics</strong></p><p><em>Infrastructure Cost per Service:</em> Tracks resource efficiency<br><em>Server to Admin Ratio:</em> Measures operations team effectiveness<br><em>Provisioning Time:</em> Provisioning time for new environments<br><em>Automated vs. Manual Work Ratio:</em> Tasks automated ratio</p><p><strong>Developer Experience Metrics</strong></p><p><em>Developer Satisfaction:</em> Regular surveys on processes and tooling<br><em>Flow Time:</em> Actual work time vs. wait time<br><em>Build Time:</em> CI pipeline execution time<br><em>Mean Time to Detect (MTTD):</em> Speed at which issues are detected</p><p><strong>Security and Compliance Metrics</strong></p><p><em>Security Scanning Coverage:</em> Code coverage for security scans<br><em>Mean Time to Remediate Vulnerabilities:</em> the speed at which security issues are remediated<br><em>Compliance Violation Detection Rate:</em> the effectiveness of automated compliance detection</p><p><strong>Customer-Centric Metrics</strong></p><p><em>Availability:</em> services up percentage of time<br><em>Response Time:</em> application performance as perceived by user<br><em>Customer Satisfaction:</em> direct measurement of software quality<br><em>Feature Usage:</em> adoption rate of new capabilities</p><p><strong>Building a Metrics Program: Best Practices</strong><br>Measuring DevOps success is more than just data capture. Build a successful metrics program with the following best practices:<br><strong>1. Start with your objectives</strong><br>Begin by deciding what business outcomes you are trying to move towards. Different goals will require different metrics:</p><ul><li>Increasing release speed? Focus on deployment frequency and lead time.</li><li>Stabilizing? Focus on MTTR and change failure rate.</li><li>Securing? Track vulnerability metrics and remediation time.</li></ul><p><strong>2. Auto-gather data</strong><br>Manual tracking results in inconsistent data and diverts time from productive work. Invest in tools that automatically measure metrics for your delivery pipeline, infrastructure, and apps.<br><strong>3. Make metrics visible</strong><br>Build dashboards that clearly show key metrics in the foreground. Visibility creates behavior change and guides teams to focus on areas of improvement.<br><strong>4. Set realistic targets</strong><br>Benchmark with industry standards but set incremental improvement targets based on your existing state. Unrealistic targets might de-motivate teams.<br><strong>5. Avoid metric manipulation</strong><br>Don’t accidentally incentivize behavior that optimizes for metrics without regard for actual improvement. Teams, for example, might break changes into small pieces so they can release more often but not get better at practice.<br><strong>6. Regular review and adjust</strong><br>Hold regular retrospectives to check metrics, identify areas for improvement, and adjust your measurement approach as needed.</p><p><strong>Pitfalls in DevOps Measurement</strong><br>Avoid these common pitfalls measuring DevOps performance:</p><ol><li>Measuring only velocity metrics with no care for quality and stability</li><li>Comprehending teams as compared to each other and not considering multiple contexts</li><li>Defining too many metrics that bring uncertainty around priorities.</li><li>Not using the data collected, turning measurement into a checkbox activity.</li><li>Ignores team feedback on what measures matter most.</li></ol><p><strong>Conclusion: Metrics as a Journey, Not a Destination</strong><br>Successful DevOps measurement isn’t about having a perfect score on every metric — it’s about leveraging data to fuel ongoing improvement. As your DevOps processes mature, your measurement strategy should mature too.<br>Begin with the DORA metrics as your base, supplement with metrics that fit your particular business goals, and build a culture where teams apply data to uncover areas for improvement instead of looking at metrics as a performance management tool.<br>Remember that the ultimate goal is not to maximize metrics for their own sake but to release better software more efficiently to wow your customers and achieve your business outcomes.<br>By building a measured measurement framework and iteratively refining it, you will not only measure your DevOps success but accelerate it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13b574891283" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>