惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

雷峰网
雷峰网
宝玉的分享
宝玉的分享
I
InfoQ
P
Privacy International News Feed
V
V2EX
IT之家
IT之家
S
SegmentFault 最新的问题
D
Darknet – Hacking Tools, Hacker News & Cyber Security
V2EX - 技术
V2EX - 技术
C
CERT Recently Published Vulnerability Notes
C
Check Point Blog
The Register - Security
The Register - Security
爱范儿
爱范儿
博客园 - 三生石上(FineUI控件)
AWS News Blog
AWS News Blog
M
MIT News - Artificial intelligence
C
Cyber Attacks, Cyber Crime and Cyber Security
F
Fortinet All Blogs
B
Blog
N
Netflix TechBlog - Medium
B
Blog RSS Feed
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Last Week in AI
Last Week in AI
T
Threatpost
Forbes - Security
Forbes - Security
U
Unit 42
A
Arctic Wolf
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
P
Palo Alto Networks Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Recorded Future
Recorded Future
L
Lohrmann on Cybersecurity
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Proofpoint News Feed
月光博客
月光博客
Spread Privacy
Spread Privacy
MongoDB | Blog
MongoDB | Blog
Jina AI
Jina AI
I
Intezer
V
Visual Studio Blog
阮一峰的网络日志
阮一峰的网络日志
The Hacker News
The Hacker News
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
L
LangChain Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园_首页
MyScale Blog
MyScale Blog
腾讯CDC
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
量子位

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Build a Self-Healing App on AWS: A Beginner's Guide
Esther Nnolu · 2026-05-27 · via DEV Community

It's midnight. You get an incident call on your phone that your application's web server has crashed, and users are seeing the dreaded 500 Internal server error. You stumble to your laptop, sleepy-eyes, to run the restart command or to run your restart script.

This is the "Old Way." It's manual, it's reactive, and it ruins your sleep.

In the world of DevOps, we don't just fix things; we build things that fix themselves (self-healing). In this article, we're going to build a simple automation that detects a web server crash and restarts the service before you even roll over in bed.

The "Healing" Architecture

To build this, we need five simple AWS resources:

  1. The Sensor (Amazon CloudWatch): The eye that monitors your server.
  2. The Tripwire (CloudWatch Alarms): The logic that says, "Wait, something is wrong."
  3. The Router (Amazon EventBridge): The nervous system that delivers the alert to our code.
  4. The Brain (AWS Lambda): The function that decides what to do.
  5. The Hands (AWS Systems Manager): The tool that actually reaches out and restarts the service.

The flow looks like this:

Step 1: Prepare your server (The EC2 instance)

First, we need a server to monitor.

  • Launch an EC2 instance: Use a t3.micro running Amazon Linux 2023 (it's Free Tier eligible). The commands in this tutorial use dnf, which is the package manager for Amazon Linux 2023. If you choose Amazon Linux 2 instead, swap dnf for yum.
  • Configure the security group. Remember to allow port 80 (HTTP) and port 22 (SSH) in your security group for this test. Without these, you won't be able to SSH into the instance or load the Nginx welcome page in your browser.
  • Attach an IAM role: This is where most beginners get stuck. Your server needs an IAM role that allows AWS Systems Manager (SSM) to talk to it. Attach the AmazonSSMManagedInstanceCore and CloudWatchAgentServerPolicy policies to your instance.

  • Start a service: SSH into your server and install Nginx:
sudo dnf update -y
sudo dnf install nginx -y
sudo systemctl enable --now nginx

Enter fullscreen mode Exit fullscreen mode

Open your browser to the instance's public IP. You should see the "Welcome to Nginx" page.

Step 2: The "Eyes" Installation (CloudWatch Agent)

The default EC2 metrics can't see inside your server. We need the agent to monitor the Nginx process.

  • Install the Agent: On your EC2, run:

sudo dnf install amazon-cloudwatch-agent -y

  • Configure the "Nginx Watcher": CloudWatch doesn't know what Nginx is until you tell it. Create a configuration file to monitor the process:

sudo nano /opt/aws/amazon-cloudwatch-agent/bin/config.json

Paste this configuration:

{
  "agent": {
    "metrics_collection_interval": 60
  },
  "metrics": {
    "namespace": "CWAgent",
    "metrics_collected": {
      "procstat": [
        {
          "exe": "nginx",
          "measurement": ["pid_count"]
        }
      ]
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Save the file and start the agen, you have to tell the agent to load the file:

sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c file:/opt/aws/amazon-cloudwatch-agent/bin/config.json -s

The agent is now running. Verify with:

sudo systemctl status amazon-cloudwatch-agent

After a minute or two, you should see a procstat_lookup pid_count metric appear in CloudWatch under the CWAgent namespace.

Step 3: Write the "Healing Script" (The Lambda)

We need a tiny function that tells AWS: "Hey, go to Instance X and restart the web server." Create a new Lambda function (Python 3.12+) and paste this code:

import os
import boto3

def lambda_handler(event, context):
    ssm = boto3.client('ssm')

    # In production, use an environment variable. Hardcoded for this lab:
    instance_id = os.environ.get('INSTANCE_ID', 'i-YOUR_INSTANCE_ID_HERE')

    alarm_name = event.get('detail', {}).get('alarmName', 'unknown')
    print(f"Alarm '{alarm_name}' triggered. Restarting Nginx on {instance_id}...")

    ssm.send_command(
        InstanceIds=[instance_id],
        DocumentName="AWS-RunShellScript",
        Parameters={'commands': ['sudo systemctl restart nginx']}
    )
    return {"status": "Restart command sent"}

Enter fullscreen mode Exit fullscreen mode

IAM permissions for the Lambda. In the Lambda console, open your function's Configuration → Permissions tab and click the execution role name to open it in IAM.

Confirm AWSLambdaBasicExecutionRole is attached (it usually is by default). Then click Add permissions → Create inline policy, switch to the JSON tab, and paste:

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": "ssm:SendCommand",
    "Resource": [
      "arn:aws:ec2:REGION:ACCOUNT_ID:instance/i-YOUR_INSTANCE_ID",
      "arn:aws:ssm:REGION::document/AWS-RunShellScript"
    ]
  }]
}

Enter fullscreen mode Exit fullscreen mode

Replace REGION, ACCOUNT_ID, and the instance ID with your values.

Step 4: Set the Tripwire (The Alarm)

Now we tell AWS when to trigger that code.
Go to CloudWatch > Alarms and click "Create Alarm."

  • Select metric: CWAgent > procstat > pid_count (filter for your Nginx process).
  • Condition: Lower than 1 (meaning Nginx is not running).
  • Missing data treatment: Treat missing data as breaching. This is important — when Nginx dies, the procstat plugin may stop reporting the metric entirely rather than reporting zero. Without this setting, the alarm may never fire.
  • Notification: You can skip the SNS step entirely. With EventBridge, you don't configure any alarm action CloudWatch automatically publishes every alarm state change to the default event bus.

Give the alarm a memorable name like nginx-down-alarm. You'll reference it in the next step.

Step 5: Route the Alarm to Lambda with EventBridge

Here's where EventBridge shines. CloudWatch Alarms publish state-change events to the default event bus automatically, we just need a rule that catches the ones we care about and sends them to our Lambda.
Go to EventBridge > Rules and click "Create rule."

  • Name: nginx-down-rule
  • Event bus: default
  • Rule type: Rule with an event pattern
  • Event source: AWS services
  • Event pattern: Use the custom pattern editor and paste this:
{
  "source": ["aws.cloudwatch"],
  "detail-type": ["CloudWatch Alarm State Change"],
  "detail": {
    "alarmName": ["nginx-down-alarm"],
    "state": {
      "value": ["ALARM"]
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

This pattern says: "Match only when this specific alarm enters the ALARM state." No filtering logic needed inside the Lambda, EventBridge handles it.

  • Target: Select "AWS service" → "Lambda function" → pick your Lambda.

EventBridge will automatically add the invoke permission on your function. No subscriptions, no topic management.

Step 6: Testing the Self-Heal

We're going to kill Nginx and watch it come back.

  • Confirm your server's IP shows the Nginx welcome page in a browser.
  • SSH into your server and stop the service: sudo systemctl stop nginx
  • Refresh the browser; the site is down.
  • Wait. Within 1–2 minutes, the metric drops, the alarm trips, EventBridge fires, Lambda runs, and SSM restarts Nginx.
  • Refresh again; The site is back up, and you didn't lift a finger.

If something doesn't fire, check the alarm history in CloudWatch first, then your Lambda's CloudWatch Logs. EventBridge also has a "Monitoring" tab on each rule showing invocation counts and failures, which is handy for debugging.

Why This Matters for Your Career

If you can walk an interviewer through this project, you're demonstrating skills that hiring managers genuinely look for in entry-level DevOps roles. You aren't just "using AWS"; you are demonstrating:

  • Event-Driven Architecture: Triggering actions based on state changes.
  • Least Privilege: Giving the Lambda only the permissions it needs.
  • MTTR (Mean Time To Recovery): You just reduced your recovery time from "whenever I wake up" to "under 120 seconds."

A Note on Cost

Most of what we used in this article fits inside the AWS Free Tier, the EC2 t3.micro, Lambda invocations, and EventBridge events from AWS services (like CloudWatch alarm state changes) are all free. One caveat: CloudWatch custom metrics (which is what procstat produces) are only free for the first 10 metrics, so a single procstat metric is fine, but the cost can scale up if you expand this pattern broadly.
When you're done experimenting, terminate the EC2 instance, delete the CloudWatch alarm, and remove the EventBridge rule to avoid any surprise bills.