SyntaxError: unterminated string literal – Python

If you are learning Python, one of the first errors you may see is:

SyntaxError: unterminated string literal

This error looks scary, but the reason is very simple:

Python found the start of a string but could not find where it ends.

Let’s understand this with easy examples.


❌ Why This Error Happens

In Python, strings must start and end with the same quote:

  • 'single quotes'
  • "double quotes"

If Python cannot find the closing quote, it throws:

👉 SyntaxError: unterminated string literal


🧪 Example 1 – Missing Closing Quote

message = "Hello World

Output

SyntaxError: unterminated string literal

✅ Fix

message = "Hello World"

🧪 Example 2 – Mixed Quotes

text = "Python is fun'

Started with double quote "
Ended with single quote '

Python gets confused → error.

✅ Fix

Use the same quotes:

text = "Python is fun"

or

text = 'Python is fun'

🧪 Example 3 – Multiline String Mistake

info = "This is line one
This is line two"

Normal quotes cannot span multiple lines.

✅ Fix 1 – Use Triple Quotes

info = """This is line one
This is line two"""

✅ Fix 2 – Use newline character

info = "This is line one\nThis is line two"

🧪 Example 4 – Quote Inside String

msg = "It's a nice day"

This works because outer quotes are double quotes.

But this fails:

msg = 'It's a nice day'

✅ Fix

Use escape character:

msg = 'It\'s a nice day'

or switch quotes:

msg = "It's a nice day"

🧠 Simple Rules to Avoid This Error

  1. Always close strings with the same quote you opened.
  2. For multiline text → use triple quotes.
  3. If your text contains quotes → use:
    • opposite quotes, or
    • escape character \.

✅ Quick Checklist

MistakeSolution
Missing quoteAdd closing quote
Mixed quotesUse same quote type
Multiline stringUse """ """
Quote inside textEscape or change quote

🎯 Interview One-Liner

“SyntaxError: unterminated string literal occurs when Python cannot find the closing quote of a string.”


✨ Final Thought

This error is not about logic —
it’s just Python saying:

“Hey, you started a string… but never told me where it ends!”

Fix the quotes → error gone 🚀

Understanding JavaScript sort() with a Simple Example

Let’s look at this JavaScript code:

const values = [32, 25, 120];
const result = values.sort();
console.log(result);

✅ Output

[120, 25, 32]

At first glance, this output feels wrong, right?
Why didn’t JavaScript sort the numbers in ascending order?

Let’s understand why this happens.


How sort() Actually Works in JavaScript

By default, JavaScript’s sort() method:

Converts elements to strings and compares them lexicographically (dictionary order).

This is the key reason for the unexpected result.


Step-by-Step Explanation

Original array:

[32, 25, 120]

JavaScript internally converts numbers to strings:

["32", "25", "120"]

Now it sorts them alphabetically:

  • "120" comes before "25" → because "1" < "2"
  • "25" comes before "32" → because "2" < "3"

So the final order becomes:

["120", "25", "32"]

Converted back to numbers:

[120, 25, 32]

Important Warning

This behavior can easily cause bugs, especially when sorting numbers.

Do NOT rely on default sort() for numeric sorting.


Correct Way to Sort Numbers

To sort numbers properly, you must provide a compare function.

Ascending Order

values.sort((a, b) => a - b);
console.log(values);

✅ Output:

[25, 32, 120]

Descending Order

values.sort((a, b) => b - a);
console.log(values);

✅ Output:

[120, 32, 25]

Why Does JavaScript Work This Way?

JavaScript was originally designed to sort strings.

So:

  • Sorting names → works perfectly
  • Sorting numbers → needs extra instruction

This is why the compare function exists.


Key Takeaways

  • array.sort() sorts strings by default
  • Numbers are converted to strings internally
  • Always use a compare function for numeric sorting
  • sort() mutates the original array

Interview One-Liner

JavaScript’s sort() method sorts values as strings by default, so numeric sorting requires a custom compare function.


✨ Final Thought

This is one of the most common JavaScript interview traps.

If you understand this:

  • You avoid bugs
  • You write safer code
  • You stand out in interviews

Small detail. Big impact 🚀


Microservices Best Practices (A Practical Guide)

Microservices architecture helps teams build scalable, flexible, and independently deployable systems.
But without the right practices, microservices can quickly become harder than a monolith.

This blog covers proven microservices best practices that work in real-world systems.


1. Keep Services Small and Focused

Each microservice should:

  • Do one business function
  • Have a single responsibility
  • Be easy to understand and maintain

❌ Bad:

One service handling users, orders, and payments

✅ Good:

  • User Service
  • Order Service
  • Payment Service

2. Each Service Owns Its Data

A microservice should own its own database.

❌ Don’t:

  • Share databases between services

✅ Do:

  • One database per service
  • Communicate via APIs

This avoids tight coupling and unexpected failures.


3. Use API-Based Communication

Services should communicate using:

  • REST APIs
  • gRPC
  • Messaging (Kafka, RabbitMQ)

Avoid:

  • Direct database access between services

4. Implement Service Discovery

In microservices, services scale up and down dynamically.

Use service discovery so services can:

  • Find each other automatically
  • Avoid hard-coded IPs or URLs

Examples:

  • Eureka
  • Consul
  • Kubernetes Service Discovery

5. Design for Failure

Failures are normal in distributed systems.

Best practices:

  • Use Circuit Breakers
  • Add timeouts
  • Implement retries with limits

Goal:

Fail fast and recover gracefully


6. Apply Rate Limiting

Protect your services from:

  • Traffic spikes
  • Abuse
  • Overload

Rate limiting ensures:

  • System stability
  • Fair usage

7. Centralized Logging and Monitoring

With many services, debugging becomes difficult.

Use:

  • Centralized logs (ELK, Loki)
  • Metrics (Prometheus)
  • Tracing (Jaeger, Zipkin)

This helps:

  • Identify failures quickly
  • Monitor system health

8. Secure Your Services

Security is critical in microservices.

Best practices:

  • Use API gateways
  • Implement authentication & authorization
  • Secure service-to-service communication (JWT, mTLS)

Never trust internal traffic blindly.


9. Make APIs Idempotent

Clients may retry requests due to network issues.

Design APIs so:

  • Multiple identical requests produce the same result
  • Duplicate actions are avoided

Especially important for:

  • Payments
  • Order creation
  • Updates

10. Use Auto Scaling

Traffic changes over time.

Auto scaling:

  • Adds resources during high load
  • Removes resources during low usage

This improves:

  • Performance
  • Cost efficiency

11. Test Services Independently

Test at multiple levels:

  • Unit tests
  • Integration tests
  • Contract tests

Each service should be:

  • Testable
  • Deployable independently

12. Avoid Over-Engineering

Microservices are powerful, but not always necessary.

Avoid microservices if:

  • Team is very small
  • Application is simple
  • No scaling requirement

Start simple, evolve when needed.


Summary: Microservices Best Practices Checklist

  • ✔ Small, focused services
  • ✔ Independent databases
  • ✔ API-based communication
  • ✔ Service discovery
  • ✔ Fault tolerance
  • ✔ Rate limiting
  • ✔ Centralized logging
  • ✔ Strong security
  • ✔ Idempotent APIs
  • ✔ Auto scaling

🎯 Final Thought

Microservices are not about splitting code —
they are about splitting responsibility wisely.

When designed correctly, microservices bring scalability, resilience, and faster development.


How Optional Chaining (?.) Saves You from Runtime Errors

While working with JavaScript objects, we often access nested properties.
But what if one property doesn’t exist?

👉 That’s where optional chaining (?.) comes to the rescue.


❌ The Common Problem

Consider this example:

const user = {};
console.log(user.profile.name);

❌ This throws an error:

Cannot read properties of undefined

Why?
Because profile does not exist, and JavaScript tries to read name from undefined.


✅ The Solution: Optional Chaining (?.)

Now look at this:

const user = {};
console.log(user.profile?.name);

✅ Output:

undefined

No error.
The program continues smoothly.


What Does ?. Actually Do?

In very simple words:

If the value exists → access it
If it doesn’t → stop and return undefined

That’s it. No crash. No exception.


Very Simple Real-Life Analogy

Imagine asking someone:

“If you have my book, please give it.
If not, that’s okay.”

Optional chaining behaves the same way 😄


Simple API Response Example

const response = {
data: {
user: {
name: "Raj"
}
}
};
console.log(response.data?.user?.name); // Raj
console.log(response.data?.user?.age); // undefined

Instead of breaking the app, JavaScript safely returns undefined.


Before vs After Optional Chaining

❌ Old Way (Using &&)

const name = user && user.profile && user.profile.name;

✅ Modern Way (Optional Chaining)

const name = user.profile?.name;

✔ Cleaner
✔ Easier to read
✔ Less error-prone


⚠️ Important Things to Remember

  • Optional chaining only reads values
  • It does not create properties
  • It works only with:
    • Objects
    • Arrays
    • Functions

❌ This is invalid:

user.profile?.name = "Raj";

Optional Chaining with Arrays

const users = [];
console.log(users[0]?.name);

✅ Output:

undefined

No error even if the array is empty.


When Should You Use Optional Chaining?

✅ API responses
✅ Nested objects
✅ Data from backend
✅ Dynamic data

❌ When you are sure the value always exists


Interview One-Liner

Optional chaining (?.) allows safe access to nested properties without throwing errors when values are null or undefined.


Final Thoughts

Optional chaining may look small, but it prevents big runtime crashes.

One operator.
Cleaner code.
Fewer bugs.

That’s the power of ?.


If this post is helpful to you don’t forget to like and subscribe !!

Architectural Concepts that Every Software Developer should know.

  1. Load Balancer

Distributes incoming traffic across multiple servers to ensure no single server gets overwhelmed.

  1. Caching

    Stores frequently accessed data in memory to reduce latency.

    1. Content Delivery Network (CDN)

    Stores static assets across globally distributed edge locations or servers so users download the content from the nearest location

    1. Message Queue

    Decouples components by letting producers enqueue messages that consumers process asynchronously.

    1. Publish-Subscribe

    Enables multiple consumers to receive messages from a topic

    1. API Gateway

    Acts as a single entry point for client requests, handling routing, authentication, rate limiting and protocol translation

    1. Circuit Breaker

    Prevents a system from repeatedly calling a failing service by temporarily stopping requests until the service recovers.

    1. Service Discovery

    Automatically tracks available service instances, enabling components to discover and communicate with each other dynamically.

    1. Sharding

    Sharding splits large datasets across multiple nodes using a shard key to improve scalability and performance.

    1. Rate Limiting

    Rate limiting controls how many requests a client can make within a time window to prevent service overload.

    1. Consistent Hashing

    Consistent hashing is a data distribution technique that minimizes data movement when nodes join or leave the system.

    1. Auto Scaling

    Auto scaling automatically adds or removes compute resources based on demand or predefined metrics.