Reading view

There are new articles available, click to refresh the page.

Locust EP 1 : Load Testing: Ensuring Application Reliability with Real-Time Examples and Metrics

In today’s fast-paced digital application, delivering a reliable and scalable application is key to providing a positive user experience.

One of the most effective ways to guarantee this is through load testing. This post will walk you through the fundamentals of load testing, real-time examples of its application, and crucial metrics to watch for.

What is Load Testing?

Load testing is a type of performance testing that simulates real-world usage of an application. By applying load to a system, testers observe how it behaves under peak and normal conditions. The primary goal is to identify any performance bottlenecks, ensure the system can handle expected user traffic, and maintain optimal performance.

Load testing answers these critical questions:

  • Can the application handle the expected user load?
  • How does performance degrade as the load increases?
  • What is the system’s breaking point?

Why is Load Testing Important?

Without load testing, applications are vulnerable to crashes, slow response times, and unavailability, all of which can lead to a poor user experience, lost revenue, and brand damage. Proactive load testing allows teams to address issues before they impact end-users.

Real-Time Load Testing Examples

Let’s explore some real-world examples that demonstrate the importance of load testing.

Example 1: E-commerce Website During a Sale Event

An online retailer preparing for a Black Friday sale knows that traffic will spike. They conduct load testing to simulate thousands of users browsing, adding items to their cart, and checking out simultaneously. By analyzing the system’s response under these conditions, the retailer can identify weak points in the checkout process or database and make necessary optimizations.

Example 2: Video Streaming Platform Launch

A new streaming platform is preparing for launch, expecting millions of users. Through load testing, the team simulates high traffic, testing how well video streaming performs under maximum user load. This testing also helps check if CDN (Content Delivery Network) configurations are optimized for global access, ensuring minimal buffering and downtime during peak hours.

Example 3: Financial Services Platform During Market Hours

A trading platform experiences intense usage during market open and close hours. Load testing helps simulate these peak times, ensuring that real-time data updates, transactions, and account management work flawlessly. Testing for these scenarios helps avoid issues like slow trade executions and platform unavailability during critical trading periods.

Key Metrics to Monitor in Load Testing

Understanding key metrics is essential for interpreting load test results. Here are some critical metrics to focus on:

1. Response Time

  • Definition: The time taken by the system to respond to a request.
  • Why It Matters: Slow response times can frustrate users and indicate bottlenecks.
  • Example Thresholds: For websites, a response time below 2 seconds is considered acceptable.

2. Throughput

  • Definition: The number of requests processed per second.
  • Why It Matters: Throughput indicates how many concurrent users your application can handle.
  • Real-Time Use Case: In our e-commerce example, the retailer would track throughput to ensure the checkout process doesn’t become a bottleneck.

3. Error Rate

  • Definition: The percentage of failed requests out of total requests.
  • Why It Matters: A high error rate could indicate application instability under load.
  • Real-Time Use Case: The trading platform monitors the error rate during market close, ensuring the system doesn’t throw errors under peak trading load.

4. CPU and Memory Utilization

  • Definition: The percentage of CPU and memory resources used during the load test.
  • Why It Matters: High CPU or memory utilization can signal that the server may not handle additional load.
  • Real-Time Use Case: The video streaming platform tracks memory usage to prevent lag or interruptions in streaming as users increase.

5. Concurrent Users

  • Definition: The number of users active on the application at the same time.
  • Why It Matters: Concurrent users help you understand how much load the system can handle before performance starts degrading.
  • Real-Time Use Case: The retailer tests how many concurrent users can shop simultaneously without crashing the website.

6. Latency

  • Definition: The time it takes for a request to travel from the client to the server and back.
  • Why It Matters: High latency indicates network or processing delays that can slow down the user experience.
  • Real-Time Use Case: For a financial app, reducing latency ensures trades execute in near real-time, which is crucial for users during volatile market conditions.

7. 95th and 99th Percentile Response Times

  • Definition: The time within which 95% or 99% of requests are completed.
  • Why It Matters: These percentiles help identify outliers that may impact user experience.
  • Real-Time Use Case: The streaming service may analyze these percentiles to ensure smooth playback for most users, even under peak loads.

Best Practices for Effective Load Testing

  1. Set Clear Objectives: Define specific goals, such as the expected number of concurrent users or acceptable response times, based on the nature of the application.
  2. Use Realistic Load Scenarios: Create scenarios that mimic actual user behavior, including peak times, user interactions, and geographical diversity.
  3. Analyze Bottlenecks and Optimize: Use test results to identify and address performance bottlenecks, whether in the application code, database queries, or server configurations.
  4. Monitor in Real-Time: Track metrics like response time, throughput, and error rates in real-time to identify issues as they arise during the test.
  5. Repeat and Compare: Conduct multiple load tests to ensure consistent performance over time, especially after any significant update or release.

Load testing is crucial for building a resilient and scalable application. By using real-world scenarios and keeping a close eye on metrics like response time, throughput, and error rates, you can ensure your system performs well under load. Proactive load testing helps to deliver a smooth, reliable experience for users, even during peak times.

Security Incident : Code Smells – Not Replaced Constants

The Secure Boot Case Study

Attackers can break through the Secure Boot process on millions of computers using Intel and ARM processors due to a leaked cryptographic key that many manufacturers used during the startup process. This key, called the Platform Key (PK), is meant to verify the authenticity of a device’s firmware and boot software.

Unfortunately, this key was leaked back in 2018. It seems that some manufacturers used this key in their devices instead of replacing it with a secure one, as was intended. As a result, millions of devices from brands like Lenovo, HP, Asus, and SuperMicro are vulnerable to attacks.

If an attacker has access to this leaked key, they can easily bypass Secure Boot, allowing them to install malicious software that can take control of the device. To fix this problem, manufacturers need to replace the compromised key and update the firmware on affected devices. Some have already started doing this, but it might take time for all devices to be updated, especially those in critical systems.

The problem is serious because the leaked key is like a master key that can unlock many devices. This issue highlights poor cryptographic key management practices, which have been a problem for many years.

What Are “Not Replaced Constants”?

In software, constants are values that are not meant to change during the execution of a program. They are often used to define configuration settings, cryptographic keys, and other critical values.

When these constants are hard-coded into a system and not updated or replaced when necessary, they become a code smell known as “Not Replaced Constants.”

Why Are They a Problem?

When constants are not replaced or updated:

  1. Security Risks: Outdated or exposed constants, such as cryptographic keys, can become security vulnerabilities. If these constants are publicly leaked or discovered by attackers, they can be exploited to gain unauthorized access or control over a system.
  2. Maintainability Issues: Hard-coded constants can make a codebase less maintainable. Changes to these values require code modifications, which can be error-prone and time-consuming.
  3. Flexibility Limitations: Systems with hard-coded constants lack flexibility, making it difficult to adapt to new requirements or configurations without altering the source code.

The Secure Boot Case Study

The recent Secure Boot vulnerability is a perfect example of the dangers posed by “Not Replaced Constants.” Here’s a breakdown of what happened:

The Vulnerability

Researchers discovered that a cryptographic key used in the Secure Boot process of millions of devices was leaked publicly. This key, known as the Platform Key (PK), serves as the root of trust during the Secure Boot process, verifying the authenticity of a device’s firmware and boot software.

What Went Wrong

The leaked PK was originally intended as a test key by American Megatrends International (AMI). However, it was not replaced by some manufacturers when producing devices for the market. As a result, the same compromised key was used across millions of devices, leaving them vulnerable to attacks.

The Consequences

Attackers with access to the leaked key can bypass Secure Boot protections, allowing them to install persistent malware and gain control over affected devices. This vulnerability highlights the critical importance of replacing test keys and securely managing cryptographic constants.

Sample Code:

Wrong

def generate_pk() -> str:
    return "DO NOT TRUST"

# Vendor forgets to replace PK
def use_default_pk() -> str:
    pk = generate_pk()
    return pk  # "DO NOT TRUST" PK used in production


Right

def generate_pk() -> str:
    # The documentation tells vendors to replace this value
    return "DO NOT TRUST"

def use_default_pk() -> str:
    pk = generate_pk()

    if pk == "DO NOT TRUST":
        raise ValueError("Error: PK must be replaced before use.")

    return pk  # Valid PK used in production

Ignoring important security steps, like changing default keys, can create big security holes. This ongoing problem shows how important it is to follow security procedures carefully. Instead of just relying on written instructions, make sure to test everything thoroughly to ensure it works as expected.

Build A Simple Alarm Clock

Creating a simple alarm clock application can be a fun project to develop programming skills. Here are the steps, input ideas, and additional features you might consider when building your alarm clock

Game Steps

  1. Define the Requirements:
    • Determine the basic functionality your alarm clock should have (e.g., set alarm, snooze, dismiss).
  2. Choose a Programming Language:
    • Select a language you are comfortable with, such as Python, JavaScript, or Java.
  3. Design the User Interface:
    • Decide if you want a graphical user interface (GUI) or a command-line interface (CLI).
  4. Implement Core Features:
    • Set Alarm: Allow users to set an alarm for a specific time.
    • Trigger Alarm: Play a sound or display a message when the alarm time is reached.
    • Snooze Functionality: Enable users to snooze the alarm for a set period.
    • Dismiss Alarm: Allow users to turn off the alarm once it’s triggered.
  5. Test the Alarm Clock:
    • Ensure that all functions work as expected and fix any bugs.
  6. Refine and Enhance:
    • Improve the interface and add additional features based on user feedback.

Input Ideas

  • Set Alarm Time:
    • Input format: “HHAM/PM” or 24-hour format “HH”.
  • Snooze Duration:
    • Allow users to input a snooze time in minutes.
  • Alarm Sound:
    • Let users choose from a list of available alarm sounds.
  • Repeat Alarm:
    • Options for repeating alarms (e.g., daily, weekdays, weekends).
  • Custom Alarm Message:
    • Input a custom message to display when the alarm goes off.

Additional Features

  • Multiple Alarms:
    • Allow users to set multiple alarms for different times and days.
  • Customizable Alarm Sounds:
    • Let users upload their own alarm sounds.
  • Volume Control:
    • Add an option to control the alarm sound volume.
  • Alarm Labels:
    • Enable users to label their alarms (e.g., “Wake Up,” “Meeting Reminder”).
  • Weather and Time Display:
    • Show current weather information and time on the main screen.
  • Recurring Alarms:
    • Allow users to set recurring alarms on specific days.
  • Dark Mode:
    • Implement a dark mode for the UI.
  • Integration with Calendars:
    • Sync alarms with calendar events or reminders.
  • Voice Control:
    • Add support for voice commands to set, snooze, or dismiss alarms.
  • Smart Alarm:
    • Implement a smart alarm feature that wakes the user at an optimal time based on their sleep cycle (e.g., using a sleep tracking app).

Implement a simple grocery list

Implementing a simple grocery list management tool can be a fun and practical project. Here’s a detailed approach including game steps, input ideas, and additional features:

Game Steps

  1. Introduction: Provide a brief introduction to the grocery list tool, explaining its purpose and how it can help manage shopping lists.
  2. Menu Options: Present a menu with options to add, view, update, delete items, and clear the entire list.
  3. User Interaction: Allow the user to select an option from the menu and perform the corresponding operation.
  4. Perform Operations: Implement functionality to add items, view the list, update quantities, delete items, or clear the list.
  5. Display Results: Show the updated grocery list and confirmation of any operations performed.
  6. Repeat or Exit: Allow the user to perform additional operations or exit the program.

Input Ideas

  1. Item Name: Allow the user to enter the name of the grocery item.
  2. Quantity: Prompt the user to specify the quantity of each item (optional).
  3. Operation Choice: Provide options to add, view, update, delete, or clear items from the list.
  4. Item Update: For updating, allow the user to specify the item and new quantity.
  5. Clear List Confirmation: Ask for confirmation before clearing the entire list.

Additional Features

  1. Persistent Storage: Save the grocery list to a file (e.g., JSON or CSV) and load it on program startup.
  2. GUI Interface: Create a graphical user interface using Tkinter or another library for a more user-friendly experience.
  3. Search Functionality: Implement a search feature to find items in the list quickly.
  4. Sort and Filter: Allow sorting the list by item name or quantity, and filtering by categories or availability.
  5. Notification System: Add notifications or reminders for items that are running low or need to be purchased.
  6. Multi-user Support: Implement features to manage multiple lists for different users or households.
  7. Export/Import: Allow users to export the grocery list to a file or import from a file.
  8. Item Categories: Organize items into categories (e.g., dairy, produce) for better management.
  9. Undo Feature: Implement an undo feature to revert the last operation.
  10. Statistics: Provide statistics on the number of items, total quantity, or other relevant data.

Implement a simple key-value storage system – Python Project

Implementing a simple key-value storage system is a great way to practice data handling and basic file operations in Python. Here’s a detailed approach including game steps, input ideas, and additional features:

Game Steps

  1. Introduction: Provide an introduction explaining what a key-value storage system is and its uses.
  2. Menu Options: Present a menu with options to add, retrieve, update, and delete key-value pairs.
  3. User Interaction: Allow the user to interact with the system based on their choice from the menu.
  4. Perform Operations: Implement functionality to perform the chosen operations (add, retrieve, update, delete).
  5. Display Results: Show the results of the operations (e.g., value retrieved or confirmation of deletion).
  6. Repeat or Exit: Allow the user to perform additional operations or exit the program.

Input Ideas

  1. Key Input: Allow the user to enter a key for operations. Ensure that keys are unique for storage operations.
  2. Value Input: Prompt the user to enter a value associated with a key. Values can be strings or numbers.
  3. Operation Choice: Present options to add, retrieve, update, or delete key-value pairs.
  4. File Handling: Optionally, allow users to specify a file to save and load the key-value pairs.
  5. Validation: Ensure that keys and values are entered correctly and handle any errors (e.g., missing keys).

Additional Features

  1. Persistent Storage: Save key-value pairs to a file (e.g., JSON or CSV) and load them on program startup.
  2. Data Validation: Implement checks to validate the format of keys and values.
  3. GUI Interface: Create a graphical user interface using Tkinter or another library for a more user-friendly experience.
  4. Search Functionality: Add a feature to search for keys or values based on user input.
  5. Data Backup: Implement a backup system to periodically save the key-value pairs.
  6. Data Encryption: Encrypt the stored data for security purposes.
  7. Command-Line Arguments: Allow users to perform operations via command-line arguments.
  8. Multi-key Operations: Support operations on multiple keys at once (e.g., batch updates).
  9. Undo Feature: Implement an undo feature to revert the last operation.
  10. User Authentication: Add user authentication to secure access to the key-value storage system.

Implement a Pomodoro technique timer.

Implementing a Pomodoro technique timer is a practical way to manage time effectively using a simple and proven productivity method. Here’s a detailed approach for creating a Pomodoro timer, including game steps, input ideas, and additional features.

Game Steps

  1. Introduction: Provide an introduction to the Pomodoro Technique, explaining that it involves working in 25-minute intervals (Pomodoros) followed by a short break, with longer breaks after several intervals.
  2. Start Timer: Allow the user to start the timer for a Pomodoro session.
  3. Timer Countdown: Display a countdown for the Pomodoro session and break periods.
  4. Notify Completion: Alert the user when the Pomodoro session or break is complete.
  5. Record Sessions: Track the number of Pomodoros completed and breaks taken.
  6. End Session: Allow the user to end the session or reset the timer if needed.
  7. Play Again Option: Offer the user the option to start a new session or stop the timer.

Input Ideas

  1. Session Duration: Allow users to set the duration for Pomodoro sessions and breaks. The default is 25 minutes for work and 5 minutes for short breaks, with a longer break (e.g., 15 minutes) after a set number of Pomodoros (e.g., 4).
  2. Custom Durations: Enable users to customize the duration of work sessions and breaks.
  3. Notification Preferences: Allow users to choose how they want to be notified (e.g., sound alert, visual alert, or popup message).
  4. Number of Pomodoros: Ask how many Pomodoro cycles the user wants to complete before taking a longer break.
  5. Reset and Stop Options: Provide options to reset the timer or stop it if needed.

Additional Features

  1. GUI Interface: Create a graphical user interface using Tkinter or another library for a more user-friendly experience.
  2. Notifications: Implement system notifications or sound alerts to notify the user when a Pomodoro or break is over.
  3. Progress Tracking: Track and display the number of completed Pomodoros and breaks, providing visual feedback on progress.
  4. Task Management: Allow users to input and track tasks they want to accomplish during each Pomodoro session.
  5. Statistics: Provide statistics on time spent working and taking breaks, possibly with visual charts or graphs.
  6. Customizable Alerts: Enable users to set custom alert sounds or messages for different stages (start, end of Pomodoro, end of break).
  7. Integration with Calendars: Integrate with calendar applications to schedule Pomodoro sessions and breaks automatically.
  8. Desktop Widgets: Create desktop widgets or applets that display the remaining time for the current session and next break.
  9. Focus Mode: Implement a focus mode that minimizes distractions by blocking certain apps or websites during Pomodoro sessions.
  10. Daily/Weekly Goals: Allow users to set and track daily or weekly productivity goals based on completed Pomodoros.

Caesar Cipher: Implement a basic encryption and decryption tool.

Caesar Cipher: https://en.wikipedia.org/wiki/Caesar_cipher

Game Steps

  1. Introduction: Provide a brief introduction to the Caesar Cipher, explaining that it’s a substitution cipher where each letter in the plaintext is shifted a fixed number of places down or up the alphabet.
  2. Choose Operation: Ask the user whether they want to encrypt or decrypt a message.
  3. Input Text: Prompt the user to enter the text they want to encrypt or decrypt.
  4. Input Shift Value: Request the shift value (key) for the cipher. Ensure the value is within a valid range (typically 1 to 25).
  5. Perform Operation: Apply the Caesar Cipher algorithm to the input text based on the user’s choice of encryption or decryption.
  6. Display Result: Show the resulting encrypted or decrypted text to the user.
  7. Play Again Option: Ask the user if they want to perform another encryption or decryption with new inputs.

Input Ideas

  1. Text Input: Allow the user to input any string of text. Handle both uppercase and lowercase letters. Decide how to treat non-alphabetic characters (e.g., spaces, punctuation).
  2. Shift Value: Ask the user for an integer shift value. Ensure it is within a reasonable range (1 to 25). Handle cases where the shift value is negative or greater than 25 by normalizing it.
  3. Mode Selection: Provide options to select between encryption and decryption. For encryption, the shift will be added; for decryption, the shift will be subtracted.
  4. Case Sensitivity: Handle uppercase and lowercase letters differently or consistently based on user preference.
  5. Special Characters: Decide whether to include special characters and spaces in the encrypted/decrypted text. Define how these characters should be treated.

Additional Features

  1. Input Validation: Implement checks to ensure the shift value is an integer and falls within the expected range. Validate that text input does not contain unsupported characters (if needed).
  2. Help/Instructions: Provide an option for users to view help or instructions on how to use the tool, explaining the Caesar Cipher and how to enter inputs.
  3. GUI Interface: Create a graphical user interface using Tkinter or another library to make the tool more accessible and user-friendly.
  4. File Operations: Allow users to read from and write to text files for encryption and decryption. This is useful for larger amounts of text.
  5. Brute Force Attack: Implement a brute force mode that tries all possible shifts for decryption and displays all possible plaintexts, useful for educational purposes or cracking simple ciphers.
  6. Custom Alphabet: Allow users to define a custom alphabet or set of characters for the cipher, making it more flexible and adaptable.
  7. Save and Load Settings: Implement functionality to save and load encryption/decryption settings, such as shift values or custom alphabets, for future use.

Build a simple version of Hangman.

Creating a simple version of Hangman is a fun way to practice programming and game logic.

Here’s a structured approach to building this game, including game steps, input ideas, and additional features to enhance it.

Game Steps (Workflow)

  1. Introduction:
    • Start with a welcome message explaining the rules of Hangman.
    • Provide brief instructions on how to play (guessing letters, how many guesses are allowed, etc.).
  2. Word Selection:
    • Choose a word for the player to guess. This can be randomly selected from a predefined list or from a file.
  3. Display State:
    • Show the current state of the word with guessed letters and placeholders for remaining letters.
    • Display the number of incorrect guesses left (hangman stages).
  4. User Input:
    • Prompt the player to guess a letter.
    • Check if the letter is in the word.
  5. Update Game State:
    • Update the display with the correct guesses.
    • Keep track of incorrect guesses and update the hangman drawing if applicable.
  6. Check for Win/Loss:
    • Determine if the player has guessed the word or used all allowed guesses.
    • Display a win or loss message based on the result.
  7. Replay Option:
    • Offer the player the option to play again or exit the game.

Input Ideas

  1. Guess Input:
    • Prompt the player to enter a single letter.
    • Validate that the input is a single alphabetic character.
  2. Replay Input:
    • After a game ends, ask the player if they want to play again (e.g., y for yes, n for no).
  3. Word List:
    • Provide a list of words to choose from, which can be hardcoded or read from a file.

Additional Features

  1. Difficulty Levels:
    • Implement difficulty levels by varying word length or allowing more or fewer incorrect guesses.
  2. Hangman Drawing:
    • Add a visual representation of the hangman that updates with each incorrect guess.
  3. Hints:
    • Offer hints if the player is struggling (e.g., reveal a letter or provide a clue).
  4. Word Categories:
    • Categorize words into themes (e.g., animals, movies) and allow players to choose a category.
  5. Score Tracking:
    • Keep track of the player’s score across multiple games and display statistics.
  6. Save and Load:
    • Allow players to save their progress and load a game later.
  7. Custom Words:
    • Allow players to input their own words for the game.
  8. Leaderboard:
    • Create a leaderboard to track high scores and player achievements.

Create a command-line to-do list application.

Creating a command-line to-do list application is a fantastic way to practice Python programming and work with basic data management. Here’s a structured approach to building this application, including game steps, input ideas, and additional features:

Game Steps (Workflow)

  1. Introduction:
    • Start with a welcome message and brief instructions on how to use the application.
    • Explain the available commands and how to perform actions like adding, removing, and viewing tasks.
  2. Main Menu:
    • Present a main menu with options for different actions:
      • Add a task
      • View all tasks
      • Mark a task as complete
      • Remove a task
      • Exit the application
  3. Task Management:
    • Implement functionality to add, view, update, and remove tasks.
    • Store tasks with details such as title, description, and completion status.
  4. Data Persistence:
    • Save tasks to a file or database so that they persist between sessions.
    • Load tasks from the file/database when the application starts.
  5. User Interaction:
    • Use input prompts to interact with the user and execute their commands.
    • Provide feedback and confirmation messages for actions taken.
  6. Exit and Save:
    • Save the current state of tasks when the user exits the application.
    • Confirm that tasks are saved and provide an exit message.

Input Ideas

  1. Command Input:
    • Use text commands to navigate the menu and perform actions (e.g., add, view, complete, remove, exit).
  2. Task Details:
    • For adding tasks, prompt the user for details like title and description.
    • Use input fields for the task details:
      • Title: Enter task title:
      • Description: Enter task description:
  3. Task Identification:
    • Use a unique identifier (like a number) or task title to reference tasks for actions such as marking complete or removing.
  4. Confirmation:
    • Prompt the user to confirm actions such as removing a task or marking it as complete.

Additional Features

  1. Task Prioritization:
    • Allow users to set priorities (e.g., low, medium, high) for tasks.
    • Implement sorting or filtering by priority.
  2. Due Dates:
    • Add due dates to tasks and provide options to view tasks by date or sort by due date.
  3. Search and Filter:
    • Implement search functionality to find tasks by title or description.
    • Add filters to view tasks by status (e.g., completed, pending) or priority.
  4. Task Categories:
    • Allow users to categorize tasks into different groups or projects.
  5. Export and Import:
    • Provide options to export tasks to a file (e.g., CSV or JSON) and import tasks from a file.
  6. User Authentication:
    • Add user authentication if multiple users need to manage their own tasks.
  7. Reminders and Notifications:
    • Implement reminders or notifications for tasks with upcoming due dates.
  8. Statistics:
    • Show statistics such as the number of completed tasks, pending tasks, or tasks by priority.

ntfy.sh – To save you from un-noticed events

Alex Pandian was the system administrator for a tech company, responsible for managing servers, maintaining network stability, and ensuring that everything ran smoothly.

With many scripts running daily and long-running processes that needed monitoring, Alex was constantly flooded with notifications.

Alex Pandian: “Every day, I have to gothrough dozens of emails and alerts just to find the ones that matter,”

Alex muttered while sipping coffee in the server room.

Alex Pandian: “There must be a better way to streamline all this information.”

Despite using several monitoring tools, the notifications from these systems were scattered and overwhelming. Alex needed a more efficient method to receive alerts only when crucial events occurred, such as script failures or the completion of resource-intensive tasks.

Determined to find a better system, Alex began searching online for a tool that could help consolidate and manage notifications.

After reading through countless forums and reviews, Alex stumbled upon a discussion about ntfy.sh, a service praised for its simplicity and flexibility.

“This looks promising,” Alex thought, excited by the ability to publish and subscribe to notifications using a straightforward, topic-based system. The idea of having notifications sent directly to a phone or desktop without needing complex configurations was exactly what Alex was looking for.

Alex decided to consult with Sam, a fellow system admin known for their expertise in automation and monitoring.

Alex Pandian: “Hey Sam, have you ever used ntfy.sh?”

Sam: “Absolutely, It’s a lifesaver for managing notifications. How do you plan to use it?”

Alex Pandian: “I’m thinking of using it for real-time alerts on script failures and long-running commands, Can you show me how it works?”

Sam: “Of course,”

with a smile, eager to guide Alex through setting up ntfy.sh to improve workflow efficiency.

Together, Sam and Alex began configuring ntfy.sh for Alex’s environment. They focused on setting up topics and integrating them with existing systems to ensure that important notifications were delivered promptly.

Step 1: Identifying Key Topics

Alex identified the main areas where notifications were needed:

  • script-failures: To receive alerts whenever a script failed.
  • command-completions: To notify when long-running commands finished.
  • server-health: For critical server health alerts.

Step 2: Subscribing to Topics

Sam showed Alex how to subscribe to these topics using ntfy.sh on a mobile device and desktop. This ensured that Alex would receive notifications wherever they were, without having to constantly check email or dashboards.


# Subscribe to topics
ntfy subscribe script-failures
ntfy subscribe command-completions
ntfy subscribe server-health

Step 3: Automating Notifications

Sam explained how to use bash scripts and curl to send notifications to ntfy.sh whenever specific events occurred.

“For example, if a script fails, you can automatically send an alert to the ‘script-failures’ topic,” Sam demonstrated.


# Notify on script failure
./backup-script.sh || curl -d "Backup script failed!" ntfy.sh/script-failures

Alex was impressed by the simplicity and efficiency of this approach. “I can automate all of this?” Alex asked.

“Definitely,” Sam replied. “You can integrate it with cron jobs, monitoring tools, and more. It’s a great way to keep track of important events without getting bogged down by noise.”

With the basics in place, Alex began applying ntfy.sh to various real-world scenarios, streamlining the notification process and improving overall efficiency.

Monitoring Script Failures

Alex set up automated alerts for critical scripts that ran daily, ensuring that any failures were immediately reported. This allowed Alex to address issues quickly, minimizing downtime and improving system reliability.


# Notify on critical script failure
./critical-task.sh || curl -d "Critical task script failed!" ntfy.sh/script-failures

Tracking Long-Running Commands

Whenever Alex initiated a long-running command, such as a server backup or data migration, notifications were sent upon completion. This enabled Alex to focus on other tasks without constantly checking on progress.


# Notify on long-running command completion
long-command && curl -d "Long command completed successfully." ntfy.sh/command-completions

Server Health Alerts

To monitor server health, Alex integrated ntfy.sh with existing monitoring tools, ensuring that any critical issues were immediately flagged.


# Send server health alert
curl -d "Server CPU usage is critically high!" ntfy.sh/server-health

As with any new tool, there were challenges to overcome. Alex encountered a few hurdles, but with Sam’s guidance, these were quickly resolved.

Challenge: Managing Multiple Notifications

Initially, Alex found it challenging to manage multiple notifications and ensure that only critical alerts were prioritized. Sam suggested using filters and priorities to focus on the most important messages.


# Subscribe with filters for high-priority alerts
ntfy subscribe script-failures --priority=high

Challenge: Scheduling Notifications

Alex wanted to schedule notifications for regular maintenance tasks and reminders. Sam introduced Alex to using cron for scheduling automated alerts.S

# Schedule notification for regular maintenance
echo "Time for weekly server maintenance." | at 8:00 AM next Saturday ntfy.sh/server-health


Sam gave some more examples to alex,

Monitoring disk space

As a system administrator, you can use ntfy.sh to receive alerts when disk space usage reaches a critical level. This helps prevent issues related to insufficient disk space.


# Check disk space and notify if usage is over 80%
disk_usage=$(df / | grep / | awk '{ print $5 }' | sed 's/%//g')
if [ $disk_usage -gt 80 ]; then
  curl -d "Warning: Disk space usage is at ${disk_usage}%." ntfy.sh/disk-space
fi

Alerting on Website Downtime

You can use ntfy.sh to monitor the status of a website and receive notifications if it goes down.


# Check website status and notify if it's down
website="https://example.com"
status_code=$(curl -o /dev/null -s -w "%{http_code}\n" $website)

if [ $status_code -ne 200 ]; then
  curl -d "Alert: $website is down! Status code: $status_code." ntfy.sh/website-monitor
fi

Reminding for Daily Tasks

You can set up ntfy.sh to send you daily reminders for important tasks, ensuring that you stay on top of your schedule.


# Schedule daily reminders
echo "Time to review your daily tasks!" | at 9:00 AM ntfy.sh/daily-reminders
echo "Stand-up meeting at 10:00 AM." | at 9:50 AM ntfy.sh/daily-reminders

Alerting on High System Load

Monitor system load and receive notifications when it exceeds a certain threshold, allowing you to take action before it impacts performance.

# Check system load and notify if it's high
load=$(uptime | awk '{ print $10 }' | sed 's/,//')
threshold=2.0

if (( $(echo "$load > $threshold" | bc -l) )); then
  curl -d "Warning: System load is high: $load" ntfy.sh/system-load
fi

Notify on Backup Completion

Receive a notification when a backup process completes, allowing you to verify its success.

# Notify on backup completion
backup_command="/path/to/backup_script.sh"
$backup_command && curl -d "Backup completed successfully." ntfy.sh/backup-status || curl -d "Backup failed!" ntfy.sh/backup-status

Notifying on Container Events with Docker

Integrate ntfy.sh with Docker to send alerts for specific container events, such as when a container stops unexpectedly.


# Notify on Docker container stop event
container_name="my_app"
container_status=$(docker inspect -f '{{.State.Status}}' $container_name)

if [ "$container_status" != "running" ]; then
  curl -d "Alert: Docker container $container_name has stopped." ntfy.sh/docker-alerts
fi

Integrating with CI/CD Pipelines

Use ntfy.sh to notify you about the status of CI/CD pipeline stages, ensuring you stay informed about build successes or failures.


# Example GitLab CI/CD YAML snippet
stages:
  - build

build_job:
  stage: build
  script:
    - make build
  after_script:
    - if [ "$CI_JOB_STATUS" == "success" ]; then
        curl -d "Build succeeded for commit $CI_COMMIT_SHORT_SHA." ntfy.sh/ci-cd-status;
      else
        curl -d "Build failed for commit $CI_COMMIT_SHORT_SHA." ntfy.sh/ci-cd-status;
      fi

Notification on ssh login to server

Lets try with docker,


FROM ubuntu:16.04
RUN apt-get update && apt-get install -y openssh-server
RUN mkdir /var/run/sshd
# Set root password for SSH access (change 'your_password' to your desired password)
RUN echo 'root:password' | chpasswd
RUN sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
COPY ntfy-ssh.sh /usr/bin/ntfy-ssh.sh
RUN chmod +x /usr/bin/ntfy-ssh.sh
RUN echo "session optional pam_exec.so /usr/bin/ntfy-ssh.sh" >> /etc/pam.d/sshd
RUN apt-get -y update; apt-get -y install curl
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D"]

script to send notification,


#!/bin/bash
if [ "${PAM_TYPE}" = "open_session" ]; then
  echo "here"
  curl \
    -H prio:high \
    -H tags:warning \
    -d "SSH login: ${PAM_USER} from ${PAM_RHOST}" \
    ntfy.sh/syed-alerts
fi

With ntfy.sh as an integral part of daily operations, Alex found a renewed sense of balance and control. The once overwhelming chaos of notifications was now a manageable stream of valuable information.

As Alex reflected on the journey, it was clear that ntfy.sh had transformed not just the way notifications were managed, but also the overall approach to system administration.

In a world full of noise, ntfy.sh had provided a clear and effective way to stay informed without distractions. For Alex, it was more than just a tool—it was a new way of managing systems efficiently.

❌