Normal view
Task 8: Number Guessing Game
GIT configure in VSCode
Create a Github account:
https://github.com/pradeep-xxx
Create a repository and choose the generated link:
https://github.com/pradeep-xxx/python_workouts.git
Use in VS code Terminal:
PS C:\Users\para\Documents\PYTHON> git init
PS C:\Users\para\Documents\PYTHON> git config --global user.name "Pradeep xxx"
PS C:\Users\para\Documents\PYTHON> git config --global user.email "pradeep.xxxx@gmail.com"
PS C:\Users\para\Documents\PYTHON> git remote add origin https://github.com/pradeep-xxx/python_works.git
PS C:\Users\para\Documents\PYTHON> git add . [OR]
git add ToDoList.py ToDoList2.py todotask.txt todotask2.txt
PS C:\Users\para\Documents\PYTHON> git commit -m "Initial Commit" [OR]
PS C:\Users\para\Documents\PYTHON> git commit -m "Add selected Python and text files" [OR]
PS C:\Users\para\Documents\PYTHON> git commit -m "Add ToDoList.py, ToDoList2.py, todotask.txt, and todotask2.txt"
PS C:\Users\para\Documents\PYTHON> git push --set-upstream origin master [OR -1st time]
PS C:\Users\para\Documents\PYTHON> git push
Redis for Python - via Docker - No direct WSL
Redis doesn’t officially support native Windows installations anymore. Instead of setting up WSL (Windows Subsystem for Linux), Docker is the easier and more modern way to run Redis on a Windows machine.
Installing Docker Desktop gives you a full environment where you can run Redis (and many other tools) without friction.
🔹 Step 1: Install Docker Desktop
Download and install Docker Desktop from:
https://www.docker.com/products/docker-desktop/
Once installed:
Make sure Docker is running (look for the whale icon in your system tray).
Enable WSL2 integration if prompted during installation.
🔹 Step 2: Pull and Run Redis
Open PowerShell or Command Prompt and run:
docker run --name my-redis -p 6379:6379 -d redis
docker ps
🔹 Step 3: Connect to Redis
docker exec -it my-redis redis-cli
set name "DockerRedis"
get name
ping
Install RedisInsight and connect to:
https://redis.io/insight/
Host: localhost
Port: 6379
To find out whether your Windows PC uses an ARM64 or AMD64 (also called x64) architecture, follow these
from Command Prompt you can run:
C:\Users\pepsara>echo %PROCESSOR_ARCHITECTURE%
AMD64
C:\Users\pepsara>docker version
Client:
Version: 28.0.4
API version: 1.48
Go version: go1.23.7
Git commit: b8034c0
Built: Tue Mar 25 15:07:48 2025
OS/Arch: windows/amd64
Context: desktop-linux
Server: Docker Desktop 4.40.0 (187762)
Engine:
Version: 28.0.4
API version: 1.48 (minimum version 1.24)
Go version: go1.23.7
Git commit: 6430e49
Built: Tue Mar 25 15:07:22 2025
OS/Arch: linux/amd64
Experimental: false
containerd:
Version: 1.7.26
GitCommit: 753481ec61c7c8955a23d6ff7bc8e4daed455734
runc:
Version: 1.2.5
GitCommit: v1.2.5-0-g59923ef
docker-init:
Version: 0.19.0
GitCommit: de40ad0
C:\Users\pepsara>docker info
✅ Step-by-Step: Use Redis with Python in VS Code
🔧 1. Install Redis client for Python
In your terminal (inside VS Code), run:
pip install redis
🧪 2. Test Redis Connection in Python
Create a new Python file, e.g., redis_test.py, and add the following code:
import redis
Connect to Redis
r = redis.Redis(host='localhost', port=6379, db=0)
Set a key
r.set('mykey', 'Hello Redis!')
Get the key
value = r.get('mykey')
print(value.decode('utf-8')) # Output: Hello Redis!
Then run it: python redis_test.py
You should see: Hello Redis!
Task 6: Tuple
1.Create a tuple containing the names of three fruits. Print the tuple and its type.
2.Given a tuple t = ("apple", "banana", "cherry"), access and print the second element.
3.Unpack the tuple t = (1, 2, 3) into variables a, b, and c, and print the variables.
4.Concatenate two tuples t1 = (1, 2) and t2 = (3, 4) and print the result.
5.Create a tuple t = ("repeat",) and repeat it three times. Print the resulting tuple.
6.Given a tuple t = (1, 2, 3, 2, 2, 4), count the number of times the number 2 appears.
7.Given a tuple t = ("a", "b", "c", "d"), find the index of the element "c".
8.Check if the element 5 is present in the tuple t = (1, 2, 3, 4)
9.Find and print the length of the tuple t = ("one", "two", "three").
10.Slice the tuple t = (0, 1, 2, 3, 4, 5) to obtain a sub-tuple containing only the elements from index 2 to 4.
11.Create a nested tuple representing a 2D point (x, y) = ((1, 2), (3,
4)). Access and print the second coordinate of the second point.
12.Try to change the value of the first element in the tuple t = (1, 2, 3) and observe what happens.
13.Convert a list l = [1, 2, 3] to a tuple and print the result. Then convert a tuple t = (4, 5, 6) to a list and print the result.
14.Create a tuple with a single item 5 and verify its type is a tuple.
15.Iterate over the tuple t = ("ParottaSalna", "is", "good") and print each element.
16.Convert the string "hello" into a tuple of characters.
17.Convert a dictionary d = {"one": 1, "two": 2} into a tuple of its items.
18.Write a function that takes a tuple of numbers and returns the sum of the numbers.
19.Use tuples as keys in a dictionary to represent points on a grid. For example, grid = {(0, 0): "origin", (1, 2): "point A"}.
Task 5: Python Function
1.Write a function greet that takes a name as an argument and prints a greeting message.
2.Write a function sum_two that takes two numbers as arguments and returns their sum.
3.Write a function is_even that takes a number as an argument and returns True if the number is even, and False if it is odd.
4.Write a function find_max that takes two numbers as arguments and returns the larger one.
5.Write a function multiplication_table that takes a number n and prints the multiplication table for n from 1 to 10.
6.Write a function celsius_to_fahrenheit that takes a temperature in Celsius and returns the temperature in Fahrenheit.
7.Write a function power that takes two arguments, a number and an exponent, and returns the number raised to the given exponent. The exponent should have a default value of 2.
TASK 4: Python Lists
1.Create a list of five delivery items and print the third item in the list. eg: [“Notebook”, “Pencil”, “Eraser”, “Ruler”, “Marker”]
2.A new delivery item “Glue Stick” needs to be added to the list. Add it to the end of the list and print the updated list.
3.Insert “Highlighter” between the second and third items and print the updated list.
4.One delivery was canceled. Remove “Ruler” from the list and print the updated list.
5.The delivery man needs to deliver only the first three items. Print a sublist containing only these items.
6.The delivery man has finished his deliveries. Convert all item names to uppercase using a list comprehension and print the new list.
7.Check if “Marker” is still in the list and print a message indicating whether it is found.
8.Print the number of delivery items in the list.
9.Sort the list of items in alphabetical order and print the sorted list.
10.The delivery man decides to reverse the order of his deliveries. Reverse the list and print it.
11.Create a list where each item is a list containing a delivery item and its delivery time. Print the first item and its time.
12.Count how many times “Ruler” appears in the list and print the count.
13.Find the index of “Pencil” in the list and print it.
14.Extend the list items with another list of new delivery items and print the updated list.
15.Clear the list of all delivery items and print the list.
16.Create a list with the item “Notebook” repeated three times and print the list.
17.Using a nested list comprehension, create a list of lists where each sublist contains an item and its length, then print the new list.
18.Filter the list to include only items that contain the letter “e” and print the filtered list.
19.Remove duplicate items from the list and print the list of unique items.
TASK 3: Slicing & Indexing
1.Write a function that takes a string and returns a new string consisting of its first and last character.
2.Write a function that reverses a given string.
3.Given a string, extract and return a substring from the 3rd to the 8th character (inclusive).
4.Write a function that returns every second character from a given string.
5.Write a function that replaces the middle third of a string with asterisks. If the length of the string is not divisible by 3, adjust the middle third accordingly.
6.Write a function that checks if a given string is a palindrome (reads the same backward as forward).
7.Given an email address, extract and return the domain.
Ans: How to find incase there are multiple occurrences? Loop?
8.Write a function that returns every third character from a given string.
9.Write a function that extracts and returns characters at even indices from a given string.
10.Write a function that skips every second character and then reverses the resulting string.
TASK 2: Constants and Variables
1.Create a variable named name and assign your name to it. Then print the value of the variable.
2.Create a variable age and assign your age to it. Later, reassign the variable with a new value and print the new value.
3.Assign the values 5, 10, and 15 to three variables a, b, and c in a single line. Print their values.
Ans:TypeError on 4th statement, because we're trying to concatenate integers (a, b, c) with strings
4.Swap the values of two variables x and y without using a third variable. Print their values before and after swapping.
5.Define constants PI with appropriate values and print them.
Ans: constants are typically written in all uppercase letters with underscores separating words. However, Python does not enforce this, so constants are not truly immutable. You can still override.
6.Write a program that calculates the area of a circle using the constant PI and a variable radius. Print the area.
Ans: ** is Squared
7.Define constants for the length and width of a rectangle. Calculate and print the area.
8.Define a constant for π (pi) and a variable for the radius. Calculate and print the circumference of the circle.
TASK 1: Python – Print exercises
1.How do you print the string “Hello, world!” to the screen?
Ans: Using sep and end Parameters is preferred way.
2.How do you print the value of a variable name which is set to “Syed Jafer” or Your name?
Ans: Note the Variable is case sensitive
3.How do you print the variables name, age, and city with labels “Name:”, “Age:”, and “City:”?
Ans: Using keyword sep="," brings in , between the Variable Name and Value itself, so avoid
4.How do you use an f-string to print name, age, and city in the format “Name: …, Age: …, City: …”?
Ans: To insert variables directly into the string used f-string
Also, you can assign values to multiple variables in a single line as seen in 1st line
5.How do you concatenate and print the strings greeting (“Hello”) and target (“world”) with a space between them?
Ans: + is used to concat the items
6.How do you print three lines of text with the strings “Line1”, “Line2”, and “Line3” on separate lines?****
7.How do you print the string He said, "Hello, world!" including the double quotes?
Ans: To print quotes inside a string, you can use either single or double quotes to enclose the string and the other type of quotes inside it.
8.How do you print the string C:\Users\Name without escaping the backslashes?
Ans: you can also use a literal backslash "\" when using Concat or Try with 'r' to treat backslashes as literal characters
9.How do you print the result of the expression 5 + 3?
10.How do you print the strings “Hello” and “world” separated by a hyphen -?
11.How do you print the string “Hello” followed by a space, and then print “world!” on the same line?
12.How do you print the value of a boolean variable is_active which is set to True?
13.How do you print the string “Hello ” three times in a row?
14.How do you print the sentence The temperature is 22.5 degrees Celsius. using the variable temperature?
15.How do you print name, age, and city using the .format() method in the format “Name: …, Age: …, City: …”?
16.How do you print the value of pi (3.14159) rounded to two decimal places in the format The value of pi is approximately 3.14?
Ans: pi is the variable & .2f formats it as a floating-point number with 2 digits after the decimal
17.How do you print the words “left” and “right” with “left” left-aligned and “right” right-aligned within a width of 10 characters each?
How to Manage Multiple Cron Job Executions
Cron jobs are a fundamental part of automating tasks in Unix-based systems. However, one common problem with cron jobs is multiple executions, where overlapping job runs can cause serious issues like data corruption, race conditions, or unexpected system load.
In this blog, we’ll explore why multiple executions happen, the potential risks, and how flock
provides an elegant solution to ensure that a cron job runs only once at a time.
The Problem: Multiple Executions of Cron Jobs
Cron jobs are scheduled to run at fixed intervals, but sometimes a new job instance starts before the previous one finishes.
This can happen due to
- Long-running jobs: If a cron job takes longer than its interval, a new instance starts while the old one is still running.
- System slowdowns: High CPU or memory usage can delay job execution, leading to overlapping runs.
- Simultaneous executions across servers: In a distributed system, multiple servers might execute the same cron job, causing duplication.
Example of a Problematic Cron Job
Let’s say we have the following cron job that runs every minute:
* * * * * /path/to/script.sh
If script.sh
takes more than a minute to execute, a second instance will start before the first one finishes.
This can lead to:
Duplicate database writes → Inconsistent data
Conflicts in file processing → Corrupt files
Overloaded system resources → Performance degradation
Real-World Example
Imagine a job that processes user invoices and sends emails
* * * * * /usr/bin/python3 /home/user/process_invoices.py
If the script takes longer than a minute to complete, multiple instances might start running, causing
- Users to receive multiple invoices.
- The database to get inconsistent updates.
- Increased server load due to excessive email sending.
The Solution: Using flock
to Prevent Multiple Executions
flock
is a Linux utility that manages file locks to ensure that only one instance of a process runs at a time. It works by locking a specific file, preventing other processes from acquiring the same lock.
Using flock
in a Cron Job
Modify the cron job as follows
* * * * * /usr/bin/flock -n /tmp/myjob.lock /path/to/script.sh
How It Works
flock -n /tmp/myjob.lock
→ Tries to acquire a lock on/tmp/myjob.lock
.- If the lock is available, the script runs.
- If the lock is already held (i.e., another instance is running),
flock
prevents the new instance from starting. -n
(non-blocking) ensures that the job doesn’t wait for the lock and simply exits if it cannot acquire it.
This guarantees that only one instance of the job runs at a time.
Verifying the Solution
You can test the lock by manually running the script with flock
/usr/bin/flock -n /tmp/myjob.lock /bin/bash -c 'echo "Running job..."; sleep 30'
Open another terminal and try to run the same command. You’ll see that the second attempt exits immediately because the lock is already acquired.
Preventing multiple executions of cron jobs is essential for maintaining data consistency, system stability, and efficiency. By using flock
, you can easily enforce single execution without complex logic.
Simple & efficient solution.
No external dependencies required.
Works seamlessly with cron jobs.
So next time you set up a cron job, add flock
and sleep peacefully knowing your tasks won’t collide.
Write a video using open-cv
Use open-cv VideoWriter function to write a video
Source Code
import cv2
video = cv2.VideoCapture("./data/video.mp4")
fourcc = cv2.VideoWriter.fourcc(*'FMP4')
writeVideo = cv2.VideoWriter('./data/writeVideo.mp4',fourcc,24,(1080,720))
while(video.isOpened()):
suc, frame = video.read()
if(suc):
frame = cv2.resize(frame,(1080,720))
cv2.imshow("write video",frame)
writeVideo.write(frame)
if(cv2.waitKey(24)&0xFF == ord('q')):
break
else:
break
writeVideo.release()
video.release()
cv2.destroyAllWindows()
Video

Pre-Required Knowledge
If you know OpenCV, you can use it to open a video. If you don’t know this, visit this open video blog.
Functions
Explain Code
Import open-cv Library import cv2
Open a Video Using videoCapture
Function
fourcc
The fourcc
function is used to specify a video codec.
Example: AVI format codec for XVID
.
VideoWriter
The videoWriter
function initializes the writeVideo
object. it specify video properties such as codec, FPS, and resolution.
There are four arguments:
- Video Path: Specifies the video write path and video name.
- fourcc: Specifies the video codec.
- FPS: Sets an FPS value.
- Resolution: Sets the video resolution.
The read()
function is used to read a frame.
After reading a frame, resize() it.
Note: If you set a resolution in writeVideo
, you must resize the frame
to the same resolution.
write
This function writes a video frame by frame into the writeVideo
object.
The waitKey
function is used to delay the program and check key events for program exit using an if condition.
Release objects
Once the writing process is complete, release the writeVideo
and video
objects to finalize the video writing process.
Additional Link
open-cv write image
Explore the OpenCV imwrite function used to write an image.
Source Code
import cv2
image = cv2.imread("./data/openCV_logo.jpg",cv2.IMREAD_GRAYSCALE)
image = cv2.resize(image,(600,600))
cv2.imwrite("./data/openCV_logo_grayscale.jpg",image)
Image

Function
Explain Code
Import the OpenCV library import cv2
.
The imread
function reads an image. Since I need a grayscale image, I set the flag value as cv2.IMREAD_GRAYSCALE
.
Resize the image using the resize()
function.
imwrite
The imwrite
function is used to save an image. It takes two arguments:
- Image path – Set the image path and name.
- Image – The image as a NumPy array.
Additional Link
open-cv open video
Playing a video in OpenCV is similar to opening an image, but it requires a loop to continuously read multiple frames.
Source Code
import cv2
video = cv2.VideoCapture("./data/video.mp4")
while(video.isOpened()):
isTrue, frame = video.read()
if(isTrue):
frame = cv2.resize(frame,(800,500))
cv2.imshow("play video",frame)
if(cv2.waitKey(24)&0xFF == ord('q')):
break
else:
break
video.release()
cv2.destroyAllWindows()
Video

Functions
Explain Program
Import OpenCV Library
import cv2
VideoCapture
This function is used to open a video by specifying a video path.
- If you pass
0
as the argument, it opens the webcam instead.
isOpened
This function returns a boolean value to check if the video or resource is opened properly.
Use while
to start a loop. with the condition isOpened()
.
read
This function reads a video frame by frame.
- It returns two values:
- Boolean:
True
if the frame is read successfully. - Frame Data: The actual video frame.
- Boolean:
Use if(isTrue)
to check if the data is properly read, then show the video.
- Resize the video resolution using
resize
function. - Show the video using
imshow
. - Exit video on keypress
if(cv2.waitKey(24)&0xFF == ord('q'))
.- Press ‘q‘ to break the video play loop.
Why Use &0xFF
?
- This ensures the if condition runs correctly.
waitKey
returns a key value, then performs an AND operation with0xFF
(which is 255 in hexadecimal).- If any number is used in an AND operation with 0xFF, it returns the same number.
Example:113 & 0xFF = 113
(same value as the first operand).
ord
The ord
function returns the ASCII value of a character.
- Example:
ord('q')
returns 113.
Finally, the if condition is validated.
If true, break the video play. Otherwise, continue playing.
release
This function releases the used resources.
destroyAllWindows()
closes all windows and cleans up used memory.
Additional Link
open-cv open image
What is OpenCV
OpenCV stands for Open Source Computer Vision. It is a library used for computer vision and machine learning tasks. It provides many functions to process images and videos.
Computer Vision
Computer vision is the process of extracting information from images or videos. For example, it can be used for object detection, face recognition, and more.
Source Code
import cv2
image = cv2.imread("./data/openCV_logo.jpg",cv2.IMREAD_COLOR)
image = cv2.resize(image,(600,600))
cv2.imshow("window title",image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Image

OpenCV Functions
imread
This function is used to read an image and returns it as a NumPy array. It requires two arguments:
- Image path: The location of the image file.
- Read flag: Specifies the mode in which the image should be read. Common flags are:
- Color Image
- Grayscale Image
- Image with Alpha Channel
resize
This function resizes an image. It requires two arguments:
- Image array: The NumPy array of the image.
- Resolution: A tuple specifying the new width and height.
imshow
This function displays an image. It takes two arguments:
- Window name: A string representing the window title.
- Image array: The image to be displayed.
waitKey
This function adds a delay to the program and listens for keypress events.
- If the value is 0, the program waits indefinitely until a key is pressed.
- If a key is pressed, it releases the program and returns the ASCII value of the pressed key.
- Example: Pressing
q
returns113
.
destroyAllWindows
This function closes all open image windows and properly cleans up used resources.
Additional Link
🎯 PostgreSQL Zero to Hero with Parottasalna – 2 Day Bootcamp (FREE!) 🚀
Databases power the backbone of modern applications, and PostgreSQL is one of the most powerful open-source relational databases trusted by top companies worldwide. Whether you’re a beginner or a developer looking to sharpen your database skills, this FREE bootcamp will take you from Zero to Hero in PostgreSQL!
What You’ll Learn?
PostgreSQL fundamentals & installation
Postgres Architecture
Writing optimized queries
Indexing & performance tuning
Transactions & locking mechanisms
Advanced joins, CTEs & subqueries
Real-world best practices & hands-on exercises
This intensive hands on bootcamp is designed for developers, DBAs, and tech enthusiasts who want to master PostgreSQL from scratch and apply it in real-world scenarios.
Who Should Attend?
Beginners eager to learn databases
Developers & Engineers working with PostgreSQL
Anyone looking to optimize their SQL skills
Date: March 22, 23 -> (Moved to April 5, 6)
Time: Will be finalized later.
Location: Online
Cost: 100% FREE
RSVP Here
Prerequisite
- Checkout this playlist of our previous postgres session https://www.youtube.com/playlist?list=PLiutOxBS1Miy3PPwxuvlGRpmNo724mAlt
This bootcamp is completely FREE – Learn without any cost!
Spots are limited – RSVP now to reserve your seat!
Boost System Performance During Traffic Surges with Spike Testing
Introduction
Spike testing is a type of performance testing that evaluates how a system responds to sudden, extreme increases in load. Unlike stress testing, which gradually increases the load, spike testing simulates abrupt surges in traffic to identify system vulnerabilities, such as crashes, slow response times, and resource exhaustion.
In this blog, we will explore spike testing in detail, covering its importance, methodology, and full implementation using K6.
Why Perform Spike Testing?
Spike testing helps you
- Determine system stability under unexpected traffic surges.
- Identify bottlenecks that arise due to rapid load increases.
- Assess auto-scaling capabilities of cloud-based infrastructures.
- Measure response time degradation during high-demand spikes.
- Ensure system recovery after the sudden load disappears.
Setting Up K6 for Spike Testing
Installing K6
# macOS brew install k6 # Ubuntu/Debian sudo apt install k6 # Using Docker docker pull grafana/k6
Choosing the Right Test Scenario
K6 provides different executors to simulate load patterns. For spike testing, we use
- ramping-arrival-rate → Gradually increases the request rate over time.
- constant-arrival-rate → Maintains a fixed number of requests per second after the spike.
Example 1: Basic Spike Test
This test starts with low traffic, spikes suddenly, and then drops back to normal.
import http from 'k6/http'; import { sleep } from 'k6'; export let options = { scenarios: { spike_test: { executor: 'ramping-arrival-rate', startRate: 10, // Start with 10 requests/sec timeUnit: '1s', preAllocatedVUs: 100, maxVUs: 500, stages: [ { duration: '30s', target: 10 }, // Low traffic { duration: '10s', target: 500 }, // Sudden spike { duration: '30s', target: 10 }, // Traffic drops ], }, }, }; export default function () { http.get('https://test-api.example.com'); sleep(1); }
Explanation
- Starts with 10 requests per second for 30 seconds.
- Spikes to 500 requests per second in 10 seconds.
- Drops back to 10 requests per second.
- Tests the system’s ability to handle and recover from traffic spikes.
Example 2: Spike Test with High User Load
This test simulates a spike in virtual users rather than just requests per second.
import http from 'k6/http'; import { sleep } from 'k6'; export let options = { scenarios: { user_spike: { executor: 'ramping-vus', stages: [ { duration: '30s', target: 20 }, // Normal traffic { duration: '10s', target: 300 }, // Sudden spike in users { duration: '30s', target: 20 }, // Drop back to normal ], }, }, }; export default function () { http.get('https://test-api.example.com'); sleep(1); }
Explanation:
- Simulates a sudden increase in concurrent virtual users (VUs).
- Helps test server stability, database handling, and auto-scaling.
Example 3: Spike Test on Multiple Endpoints
In real-world applications, multiple endpoints may experience spikes simultaneously. Here’s how to test different API routes.
import http from 'k6/http'; import { sleep } from 'k6'; export let options = { scenarios: { multiple_endpoint_spike: { executor: 'ramping-arrival-rate', startRate: 5, timeUnit: '1s', preAllocatedVUs: 200, maxVUs: 500, stages: [ { duration: '20s', target: 10 }, // Normal traffic { duration: '10s', target: 300 }, // Spike across endpoints { duration: '20s', target: 10 }, // Traffic drop ], }, }, }; export default function () { let urls = [ 'https://test-api.example.com/users', 'https://test-api.example.com/orders', 'https://test-api.example.com/products' ]; let res = http.get(urls[Math.floor(Math.random() * urls.length)]); console.log(`Response time: ${res.timings.duration}ms`); sleep(1); }
Explanation
- Simulates traffic spikes across multiple API endpoints.
- Helps identify which API calls suffer under extreme load.
Analyzing Test Results
After running the tests, K6 provides key performance metrics
http_req_duration......: avg=350ms min=150ms max=3000ms http_reqs..............: 10,000 requests vus_max................: 500 errors.................: 2%
Key Metrics
- http_req_duration → Measures response time impact.
- vus_max → Peak virtual users during the spike.
- errors → Percentage of failed requests due to overload.
Best Practices for Spike Testing
- Monitor application logs and database performance during the test.
- Use auto-scaling mechanisms for cloud-based environments.
- Combine spike tests with stress testing for better insights.
- Analyze error rates and recovery time to ensure system stability.
Spike testing is crucial for ensuring application stability under sudden, unpredictable traffic surges. Using K6, we can simulate spikes in both requests per second and concurrent users to identify bottlenecks before they impact real users.
How Stress Testing Can Make More Attractive Systems ?
Introduction
Stress testing is a critical aspect of performance testing that evaluates how a system performs under extreme loads. Unlike load testing, which simulates expected user traffic, stress testing pushes a system beyond its limits to identify breaking points and measure recovery capabilities.
In this blog, we will explore stress testing using K6, an open-source load testing tool, with detailed explanations and full examples to help you implement stress testing effectively.
Why Stress Testing?
Stress testing helps you
- Identify the maximum capacity of your system.
- Detect potential failures and bottlenecks.
- Measure system stability and recovery under high loads.
- Ensure infrastructure can handle unexpected spikes in traffic.
Setting Up K6 for Stress Testing
Installing K6
# macOS brew install k6 # Ubuntu/Debian sudo apt install k6 # Using Docker docker pull grafana/k6
Understanding Stress Testing Scenarios
K6 provides various executors to simulate different traffic patterns. For stress testing, we mainly use
- ramping-vus – Gradually increases virtual users to a high level.
- constant-vus – Maintains a fixed high number of virtual users.
- spike – Simulates a sudden surge in traffic.
Example 1: Basic Stress Test with Ramping VUs
This script gradually increases the number of virtual users, holds a peak load, and then reduces it.
import http from 'k6/http'; import { sleep } from 'k6'; export let options = { stages: [ { duration: '1m', target: 100 }, // Ramp up to 100 users in 1 min { duration: '3m', target: 100 }, // Stay at 100 users for 3 min { duration: '1m', target: 0 }, // Ramp down to 0 users ], }; export default function () { let res = http.get('https://test-api.example.com'); sleep(1); }
Explanation
- The test starts with 0 users and ramps up to 100 users in 1 minute.
- Holds 100 users for 3 minutes.
- Gradually reduces load to 0 users.
- The
sleep(1)
function helps simulate real user behavior between requests.
Example 2: Constant High Load Test
This test maintains a consistently high number of virtual users.
import http from 'k6/http'; import { sleep } from 'k6'; export let options = { vus: 200, // 200 virtual users duration: '5m', // Run the test for 5 minutes }; export default function () { http.get('https://test-api.example.com'); sleep(1); }
Explanation
- 200 virtual users are constantly hitting the endpoint for 5 minutes.
- Helps evaluate system performance under sustained high traffic.
Example 3: Spike Testing (Sudden Traffic Surge)
This test simulates a sudden spike in traffic, followed by a drop.
import http from 'k6/http'; import { sleep } from 'k6'; export let options = { stages: [ { duration: '10s', target: 10 }, // Start with 10 users { duration: '10s', target: 500 }, // Spike to 500 users { duration: '10s', target: 10 }, // Drop back to 10 users ], }; export default function () { http.get('https://test-api.example.com'); sleep(1); }
Explanation
- Starts with 10 users.
- Spikes suddenly to 500 users in 10 seconds.
- Drops back to 10 users.
- Helps determine how the system handles sudden surges in traffic.
Analyzing Test Results
After running the tests, K6 provides detailed statistics
checks..................: 100.00% ✓ 5000 ✗ 0 http_req_duration......: avg=300ms min=200ms max=2000ms http_reqs..............: 5000 requests vus_max................: 500
Key Metrics to Analyze
- http_req_duration → Measures response time.
- vus_max → Maximum concurrent virtual users.
- http_reqs → Total number of requests.
- errors → Number of failed requests.
Stress testing is vital to ensure application stability and scalability. Using K6, we can simulate different stress scenarios like ramping load, constant high load, and spikes to identify system weaknesses before they affect users.