Bird
Raised Fist0
Denoframework~15 mins

Health checks and monitoring in Deno - Deep Dive

Choose your learning style10 modes available
Overview - Health checks and monitoring
What is it?
Health checks and monitoring are ways to keep an eye on a running application or service to make sure it is working well. Health checks are simple tests that tell if the app is alive and responsive. Monitoring collects data over time to spot problems early and understand how the app behaves. Together, they help keep software reliable and fast.
Why it matters
Without health checks and monitoring, problems in an app can go unnoticed until users complain or the app crashes badly. This can cause lost customers, bad reputation, and wasted time fixing urgent issues. Health checks and monitoring let developers catch problems early, fix them quickly, and keep users happy with smooth service.
Where it fits
Before learning this, you should know basic Deno app development and how servers work. After this, you can learn about advanced observability tools, alerting systems, and automated recovery techniques to build resilient apps.
Mental Model
Core Idea
Health checks are quick tests to confirm an app is alive, while monitoring watches its behavior over time to catch issues early.
Think of it like...
It's like checking your car's engine light (health check) to see if it runs now, and using a dashboard camera and sensors (monitoring) to track its performance and spot problems before they cause a breakdown.
┌───────────────┐       ┌───────────────┐
│   Health      │       │  Monitoring   │
│   Checks      │──────▶│  Data & Logs  │
│ (Is app alive?)│       │ (Track over   │
└───────────────┘       │  time)        │
                        └───────────────┘
                               │
                               ▼
                      ┌─────────────────┐
                      │  Alerts & Fixes │
                      └─────────────────┘
Build-Up - 7 Steps
1
FoundationWhat Are Health Checks
🤔
Concept: Health checks are simple ways to ask if an app is running and ready to serve requests.
In Deno, a health check can be a special URL endpoint like '/health' that returns a quick response such as 'OK'. This tells other systems or users that the app is alive. For example, a server might respond with status 200 and a message 'Healthy' when this endpoint is called.
Result
When you visit the health check URL, you get a quick confirmation the app is running.
Understanding health checks helps you build apps that can tell others when they are ready or if they have stopped working.
2
FoundationBasics of Monitoring
🤔
Concept: Monitoring means collecting data about your app's performance and behavior over time.
Monitoring in Deno can involve logging requests, tracking response times, and recording errors. This data is stored and analyzed to see trends or spot unusual behavior. Tools can visualize this data in graphs or dashboards.
Result
You get a history of how your app performs, helping you notice slowdowns or errors before users do.
Knowing how to monitor your app gives you a window into its health beyond just 'alive or dead'.
3
IntermediateImplementing Health Checks in Deno
🤔Before reading on: do you think a health check should check only if the server is running, or also if the database is connected? Commit to your answer.
Concept: Health checks can be simple or complex, checking not just the app but also its dependencies.
A basic health check in Deno might just return 'OK'. A more advanced one can check if the database connection is alive or if other services are reachable. This is done by adding code that tests these dependencies and returns a failure status if any are down.
Result
Health check endpoints give more accurate status, helping detect deeper problems early.
Understanding that health checks can include dependencies helps prevent false positives where the app is running but can't serve properly.
4
IntermediateSetting Up Monitoring with Logs and Metrics
🤔Before reading on: do you think logs alone are enough for monitoring, or do you need metrics too? Commit to your answer.
Concept: Effective monitoring combines logs (records of events) and metrics (numeric data) for a full picture.
In Deno, you can log every request and error to a file or external service. Metrics like request count, error rate, and response time can be collected using libraries or custom code. These metrics can be sent to monitoring platforms for visualization and alerting.
Result
You get detailed insights into app behavior and can detect issues like slow responses or spikes in errors.
Knowing the difference and use of logs and metrics helps build a monitoring system that catches problems early and clearly.
5
IntermediateUsing Third-Party Monitoring Tools
🤔
Concept: You can connect your Deno app to external monitoring services for easier setup and better analysis.
Many tools like Prometheus, Grafana, or Datadog can collect metrics and logs from your app. You add code or middleware in Deno to send data to these tools. They provide dashboards, alerts, and historical data without building everything yourself.
Result
You have professional-grade monitoring with less effort and better visualization.
Leveraging existing tools saves time and gives you powerful features that would be hard to build alone.
6
AdvancedHealth Checks and Monitoring in Production
🤔Before reading on: do you think health checks should be public endpoints or protected? Commit to your answer.
Concept: In production, health checks and monitoring must be secure, efficient, and integrated with deployment systems.
Health check endpoints should be lightweight and may be protected or limited to internal networks to avoid misuse. Monitoring data should be collected with minimal performance impact. Integration with orchestration tools like Kubernetes uses health checks to restart unhealthy apps automatically.
Result
Your app stays reliable and recovers quickly from failures without exposing sensitive info.
Knowing production best practices prevents security risks and ensures your monitoring helps maintain uptime.
7
ExpertAdvanced Monitoring: Distributed Tracing and Alerts
🤔Before reading on: do you think monitoring only needs metrics, or can tracing add value? Commit to your answer.
Concept: Distributed tracing tracks requests across multiple services to find where delays or errors happen.
In complex Deno apps with microservices, tracing tools record the path of a request through each service. This helps pinpoint slow or failing parts. Alerts can be set up to notify teams immediately when metrics cross thresholds or traces show errors.
Result
You can quickly diagnose and fix problems in complex systems before users notice.
Understanding tracing and alerting elevates monitoring from passive observation to active problem solving.
Under the Hood
Health checks work by exposing a simple endpoint that returns a status code and message quickly. Monitoring collects logs and metrics by intercepting app events like requests and errors, then stores or sends this data to analysis tools. In Deno, this often uses middleware or event hooks. Distributed tracing adds unique IDs to requests to follow them across services.
Why designed this way?
Health checks are designed to be lightweight to avoid adding load or delays. Monitoring separates data collection from analysis to keep apps fast and flexible. Distributed tracing was created to solve the problem of debugging complex, multi-service apps where logs alone are not enough.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│  Client or    │──────▶│ Health Check  │──────▶│  Status Code  │
│  Orchestrator │       │  Endpoint     │       │  & Message    │
└───────────────┘       └───────────────┘       └───────────────┘

┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│  App Events   │──────▶│  Monitoring   │──────▶│  Logs &       │
│ (Requests,    │       │  Middleware   │       │  Metrics      │
│  Errors)      │       └───────────────┘       └───────────────┘
└───────────────┘

┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Distributed   │──────▶│ Trace Context │──────▶│  Trace Storage│
│ Tracing IDs   │       │ Propagation   │       │  & Analysis   │
└───────────────┘       └───────────────┘       └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Is a health check enough to guarantee your app is fully functional? Commit yes or no.
Common Belief:If the health check endpoint returns OK, the app is fully healthy and serving all features.
Tap to reveal reality
Reality:A health check usually only confirms the app is running, not that all features or dependencies work correctly.
Why it matters:Relying only on health checks can miss deeper problems like database failures, causing unexpected downtime.
Quick: Do logs alone provide all the information needed for monitoring? Commit yes or no.
Common Belief:Logging every event is enough to monitor app health and performance.
Tap to reveal reality
Reality:Logs are useful but metrics provide summarized, numeric data that is easier to analyze and alert on.
Why it matters:Without metrics, you may miss trends or spikes that logs alone don't clearly show, delaying problem detection.
Quick: Should health check endpoints be publicly accessible? Commit yes or no.
Common Belief:Health check URLs should be open to everyone so anyone can check app status.
Tap to reveal reality
Reality:Public health check endpoints can expose sensitive info or be abused; they should be protected or limited to trusted users.
Why it matters:Exposing health checks publicly can lead to security risks or denial of service attacks.
Quick: Does monitoring add significant performance overhead to your app? Commit yes or no.
Common Belief:Monitoring always slows down your app noticeably.
Tap to reveal reality
Reality:Properly designed monitoring uses lightweight data collection and asynchronous reporting to minimize impact.
Why it matters:Believing monitoring is too costly may lead teams to skip it, increasing risk of unnoticed failures.
Expert Zone
1
Health checks can be layered: simple liveness checks and deeper readiness checks that verify dependencies before traffic is routed.
2
Monitoring data should be correlated with deployment and configuration changes to understand cause-effect relationships.
3
Distributed tracing requires careful context propagation and sampling strategies to avoid overwhelming storage and maintain performance.
When NOT to use
Health checks and monitoring are less useful for very simple scripts or one-off tasks where uptime and performance are not critical. In such cases, manual checks or simple logs may suffice. For complex distributed systems, specialized observability platforms are better than homegrown solutions.
Production Patterns
In production, health checks integrate with container orchestrators like Kubernetes to automate restarts. Monitoring uses alerting rules to notify teams via email or chat when thresholds are crossed. Tracing is combined with logs and metrics in unified dashboards for faster debugging.
Connections
DevOps
Health checks and monitoring are foundational practices in DevOps for continuous delivery and reliability.
Understanding health checks helps grasp how automated deployment systems keep apps running smoothly without manual intervention.
Cybersecurity
Health check endpoints must be secured to prevent information leaks and attacks.
Knowing monitoring security helps prevent attackers from exploiting status endpoints to find vulnerabilities.
Human Physiology
Monitoring an app's health is like monitoring vital signs in a human body to detect illness early.
This cross-domain link shows how continuous observation and quick checks keep complex systems alive and healthy.
Common Pitfalls
#1Exposing detailed health check info publicly.
Wrong approach:app.get('/health', (ctx) => { ctx.response.body = { status: 'ok', db: 'connected', secretKey: '12345' }; });
Correct approach:app.get('/health', (ctx) => { ctx.response.body = { status: 'ok' }; });
Root cause:Misunderstanding that health checks should reveal internal secrets or sensitive info.
#2Relying only on a simple 'OK' health check without checking dependencies.
Wrong approach:app.get('/health', (ctx) => { ctx.response.body = 'OK'; }); // no checks for DB or services
Correct approach:app.get('/health', async (ctx) => { const dbOk = await checkDatabase(); ctx.response.body = dbOk ? 'OK' : 'DB Error'; });
Root cause:Assuming app running means all parts are healthy.
#3Logging everything synchronously causing slow responses.
Wrong approach:app.use(async (ctx, next) => { logSync(ctx.request); await next(); });
Correct approach:app.use(async (ctx, next) => { logAsync(ctx.request); await next(); });
Root cause:Not understanding performance impact of blocking operations in request handling.
Key Takeaways
Health checks are simple endpoints that confirm if an app is alive and ready, but they should also verify key dependencies for accuracy.
Monitoring collects logs and metrics over time to give a full picture of app health and performance, enabling early problem detection.
In production, health checks and monitoring must be secure, efficient, and integrated with deployment tools to maintain reliability.
Advanced monitoring includes distributed tracing and alerting to diagnose complex issues quickly in multi-service systems.
Understanding these concepts helps build resilient, observable apps that keep users happy and reduce downtime.

Practice

(1/5)
1. What is the main purpose of a health check endpoint in a Deno application?
easy
A. To verify if the application is running and responsive
B. To deploy the application to production
C. To increase the application's memory usage
D. To compile the Deno code into machine code

Solution

  1. Step 1: Understand health check concept

    A health check endpoint is designed to confirm that the app is alive and responding to requests.
  2. Step 2: Identify the correct purpose

    Options B, C, and D describe unrelated tasks like deployment, resource usage, or compilation, which are not health checks.
  3. Final Answer:

    To verify if the application is running and responsive -> Option A
  4. Quick Check:

    Health check = Verify app responsiveness [OK]
Hint: Health checks confirm app is alive and responding [OK]
Common Mistakes:
  • Confusing health checks with deployment steps
  • Thinking health checks improve performance directly
  • Mixing health checks with code compilation
2. Which of the following is the correct way to create a simple health check HTTP endpoint in Deno?
easy
A. import { serve } from "https://deno.land/std/http/server.ts"; serve(req => console.log(req), { port: 8000 });
B. import { listenAndServe } from "https://deno.land/std/http/server.ts"; listenAndServe(8000, () => console.log("OK"));
C. import { serve } from "https://deno.land/std/http/server.ts"; serve(() => console.log("OK"), { port: 8000 });
D. import { serve } from "https://deno.land/std/http/server.ts"; serve(req => new Response("OK"), { port: 8000 });

Solution

  1. Step 1: Check correct import and usage

    import { serve } from "https://deno.land/std/http/server.ts"; serve(req => new Response("OK"), { port: 8000 }); correctly imports 'serve' and returns a Response with "OK" for each request, which is a valid health check endpoint.
  2. Step 2: Identify incorrect usage in other options

    import { listenAndServe } from "https://deno.land/std/http/server.ts"; listenAndServe(8000, () => console.log("OK")); uses deprecated 'listenAndServe' and does not respond to requests properly. Options A and C use console.log instead of returning a Response, so they won't respond correctly.
  3. Final Answer:

    import { serve } from "https://deno.land/std/http/server.ts"; serve(req => new Response("OK"), { port: 8000 }); -> Option D
  4. Quick Check:

    serve + Response("OK") = Correct health endpoint [OK]
Hint: Use serve with a Response object to reply to requests [OK]
Common Mistakes:
  • Using console.log instead of returning Response
  • Using deprecated functions like listenAndServe
  • Not returning a response to HTTP requests
3. Given this Deno code snippet for a health check endpoint, what will be the output when accessed via HTTP?
import { serve } from "https://deno.land/std/http/server.ts";
serve(req => {
  if (new URL(req.url).pathname === "/health") {
    return new Response("Healthy", { status: 200 });
  } else {
    return new Response("Not Found", { status: 404 });
  }
}, { port: 8080 });
medium
A. Response with body 'Healthy' and status 404 when URL is '/health'
B. Response with body 'Healthy' and status 200 when URL is '/health'
C. Response with body 'Not Found' and status 200 for all URLs
D. Server crashes due to syntax error

Solution

  1. Step 1: Analyze request URL condition

    The code checks if the request URL is exactly '/health'. If yes, it returns a 200 status with "Healthy".
  2. Step 2: Understand else branch

    If the URL is anything else, it returns a 404 status with "Not Found".
  3. Final Answer:

    Response with body 'Healthy' and status 200 when URL is '/health' -> Option B
  4. Quick Check:

    URL '/health' = 200 Healthy [OK]
Hint: Check URL condition to predict response status and body [OK]
Common Mistakes:
  • Confusing status codes for different URLs
  • Assuming server crashes without syntax errors
  • Mixing response body and status code
4. You wrote this Deno health check server code but it does not respond to requests properly. What is the error?
import { serve } from "https://deno.land/std/http/server.ts";
serve(req => {
  console.log("Received request");
});
medium
A. The serve function requires a port number as a string
B. The import statement is incorrect
C. The handler does not return a Response object
D. console.log is not allowed inside serve

Solution

  1. Step 1: Check handler function

    The handler function only logs to console but does not return any Response, so HTTP requests get no valid reply.
  2. Step 2: Verify other parts

    The import is correct, serve accepts an options object for port, and console.log is allowed. The main issue is missing Response return.
  3. Final Answer:

    The handler does not return a Response object -> Option C
  4. Quick Check:

    Handler must return Response [OK]
Hint: Always return a Response object in serve handler [OK]
Common Mistakes:
  • Forgetting to return Response in handler
  • Thinking console.log sends HTTP response
  • Misunderstanding serve function parameters
5. You want to monitor your Deno app's health and expose metrics like uptime and request count. Which approach best combines health checks and monitoring in one server?
hard
A. Create two endpoints: '/health' returns 200 OK; '/metrics' returns JSON with uptime and request count
B. Use only '/health' endpoint returning plain text 'OK' without metrics
C. Create a single endpoint that returns HTML with uptime but no status code
D. Run two separate Deno servers, one for health and one for metrics, on different ports

Solution

  1. Step 1: Understand combined health and monitoring needs

    Health checks confirm app is alive; monitoring provides metrics like uptime and request count.
  2. Step 2: Evaluate options for best practice

    Create two endpoints: '/health' returns 200 OK; '/metrics' returns JSON with uptime and request count cleanly separates concerns with '/health' for status and '/metrics' for detailed data, both accessible on one server.
  3. Step 3: Reject less effective options

    Use only '/health' endpoint returning plain text 'OK' without metrics lacks metrics, C lacks proper status code, D adds complexity by running two servers unnecessarily.
  4. Final Answer:

    Create two endpoints: '/health' returns 200 OK; '/metrics' returns JSON with uptime and request count -> Option A
  5. Quick Check:

    Separate endpoints for health and metrics = Best practice [OK]
Hint: Use separate endpoints for health and metrics on same server [OK]
Common Mistakes:
  • Mixing metrics and health in one endpoint without status code
  • Ignoring metrics in health checks
  • Running multiple servers unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard