class UserService { private UserRepository userRepo; private EmailService emailService; public User createUser(UserRequest request) { // Validation logic // Business rules // Database operations }}
2. Database Schema
CREATE TABLE users ( id BIGINT PRIMARY KEY, email VARCHAR(255) UNIQUE NOT NULL, password_hash VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT NOW() -- UNIQUE on email already creates an index; no separate idx_email needed);CREATE TABLE posts ( id BIGINT PRIMARY KEY, user_id BIGINT REFERENCES users(id), content TEXT NOT NULL, created_at TIMESTAMP DEFAULT NOW());-- Inline INDEX inside CREATE TABLE is MySQL-only; portable (PostgreSQL) form:CREATE INDEX idx_user_created ON posts (user_id, created_at);
import bisect, hashlibdef stable_hash(s): # Python's built-in hash() is randomised per process for str -> use a stable hash return int(hashlib.md5(s.encode()).hexdigest(), 16) % (2**32)def consistent_hash(key, ring): """ Distribute keys across nodes using consistent hashing. ring: list of (hash_value, node) sorted by hash_value (add several virtual nodes per physical node for balance) """ hashes = [h for h, _ in ring] i = bisect.bisect_left(hashes, stable_hash(key)) # first node with hash >= key hash return ring[i % len(ring)][1] # wrap around to smallest hash
Design Patterns
Repository Pattern
interface UserRepository { User save(User user); Optional<User> findById(Long id); Optional<User> findByEmail(String email); // email is UNIQUE}
Factory Pattern
class NotificationFactory: @staticmethod def create_notification(type, message): if type == "email": return EmailNotification(message) elif type == "sms": return SMSNotification(message)
Geographically distributed network of servers that deliver content to users from the nearest location
What is CDN?
A CDN is a network of strategically placed servers (edge servers) around the world that cache and deliver content to users from the closest geographical location.
Purpose:
Reduce Latency → Faster content delivery
Improve Performance → Better user experience
Reduce Server Load → Distribute traffic
Increase Availability → Redundancy and fault tolerance
How CDN Works
Basic Flow:
1. User requests content (e.g., image, video, webpage)
2. DNS routes request to nearest CDN edge server
3. If content exists in cache → Return cached content
4. If not in cache → Fetch from origin server
5. Cache content at edge server for future requests
6. Return content to user
Architecture Diagram:
[User in NYC] → [CDN Edge NYC] → [Origin Server California]
[User in London] → [CDN Edge London] → [Origin Server California]
[User in Tokyo] → [CDN Edge Tokyo] → [Origin Server California]
CDN Components
1. Edge Servers (PoP - Point of Presence)
Location: Major cities worldwide
Function: Cache and serve content
Capacity: High-performance SSD storage
Examples: 100+ locations globally
2. Origin Server
Source: Original content location
Backup: Authoritative content source
Updates: Push updates to edge servers
3. Cache Management
TTL: Time-to-live for cached content
Invalidation: Remove outdated content
Prefetching: Proactively cache popular content
4. Load Balancers
Traffic Distribution: Route to best edge server
Health Checks: Monitor server availability
Failover: Redirect if server fails
CDN Types
1. Traditional Pull CDN
On-demand: Content cached when first requested
Lazy Loading: Cache-miss triggers origin fetch
Best For: General web content, images
User Request → Edge Server (cache miss) → Origin Server
↓ (cache content)
User Request → Edge Server (cache hit) → Direct response
2. Push CDN
Proactive: Content pushed to edge servers
Scheduled: Regular content updates
Best For: Static content, scheduled releases
Origin Server → Push content → All Edge Servers
User Request → Edge Server → Cached content (always available)
3. Hybrid CDN
Combination: Both pull and push strategies
Intelligent: Based on content type and usage patterns
Optimal: Best of both approaches
CDN Caching Strategies
1. Cache-Control Headers
Cache-Control: public, max-age=31536000 # 1 yearCache-Control: private, no-store # Don't cache at allCache-Control: no-cache # Store, but revalidate with origin before each useCache-Control: public, s-maxage=3600 # CDN cache 1 hour
2. Content Types & TTL
Content Type
TTL
Reason
Static Images
1 year
Rarely change
CSS/JS Files
1 month
Version controlled
HTML Pages
1 hour
Dynamic content
API Responses
5 minutes
Real-time data
User Profiles
No cache
Personal data
3. Cache Invalidation
// Purge specific filecdn.purge('/images/logo.png');// Purge by patterncdn.purge('/css/*');// Purge by tagscdn.purgeByTags(['product-123', 'category-electronics']);
Geographic Distribution
CDN Locations (Examples)
North America:
- East Coast: New York, Atlanta, Miami
- West Coast: Los Angeles, San Francisco, Seattle
- Central: Chicago, Dallas, Denver
Europe:
- Western: London, Paris, Amsterdam, Frankfurt
- Eastern: Warsaw, Prague, Moscow
Asia-Pacific:
- East Asia: Tokyo, Seoul, Hong Kong, Singapore
- South Asia: Mumbai, Bangalore
- Oceania: Sydney, Melbourne
Routing Methods
DNS-based: GeoDNS routes to nearest server
Anycast: Same IP, different physical servers
HTTP Redirect: Application-level routing
Performance Benefits
Latency Reduction
Without CDN:
User (NYC) → Server (California) = ~4000km = ~60-80ms RTT (fibre floor ~40ms)
With CDN:
User (NYC) → CDN Edge (NYC) = ~50km = a few ms RTT
Large latency reduction (exact savings depend on route)
Bandwidth Optimization
Compression: Gzip, Brotli compression
Image Optimization: WebP, AVIF formats
Minification: Remove unnecessary characters
HTTP/2: Multiplexing, header compression
Concurrent Connections
HTTP/1.1 browser limit: ~6 connections per domain
Legacy HTTP/1.1 workaround (domain sharding): multiple subdomains
- cdn1.example.com
- cdn2.example.com
- cdn3.example.com
Result: 18 concurrent connections
HTTP/2 & HTTP/3: one connection multiplexes all requests → domain sharding
is an anti-pattern (extra DNS/TLS handshakes, breaks prioritisation)
Security Features
DDoS Protection
Traffic Filtering: Block malicious requests
Rate Limiting: Prevent abuse
Geographic Blocking: Restrict by country
Bot Protection: CAPTCHA challenges
SSL/TLS Termination
User → [HTTPS] → CDN Edge → [HTTPS, origin cert validated] → Origin Server
Benefits:
- Offload SSL processing from origin
- Latest TLS versions at edge
- Certificate management
Web Application Firewall (WAF)
SQL Injection: Block malicious SQL queries
XSS Protection: Filter cross-site scripting
OWASP Top 10: Protection against common attacks
Popular CDN Providers
Major Players
Provider
Strengths
Use Cases
Cloudflare
Security, DNS, Edge computing
General purpose, security-focused
AWS CloudFront
AWS integration, global reach
AWS ecosystem, enterprise
Akamai
Largest network, enterprise features
Large enterprises, streaming
Fastly
Real-time purging, edge computing
Developer-friendly, real-time apps
Google Cloud CDN
GCP integration, YouTube network
Google ecosystem, video content
Azure CDN
Microsoft integration, enterprise
Microsoft ecosystem, enterprise
Specialized CDNs
Video: Wowza, JW Player, Brightcove (video platforms that run on top of CDNs, not CDNs themselves)
Gaming: Game downloads are served by general CDNs (Akamai, CloudFront, etc.); Amazon GameLift hosts game servers and is not a CDN (Google Stadia shut down Jan 2023)
Mobile: Akamai Ion
Implementation Examples
1. Basic CDN Setup
<!-- Before CDN --><img src="https://example.com/images/logo.png" alt="Logo"><link rel="stylesheet" href="https://example.com/css/style.css"><!-- After CDN --><img src="https://cdn.example.com/images/logo.png" alt="Logo"><link rel="stylesheet" href="https://cdn.example.com/css/style.css">
2. Dynamic Content Caching
// Cache API responses with short TTLapp.get('/api/products', (req, res) => { res.set({ 'Cache-Control': 'public, max-age=300', // 5 minutes 'Vary': 'Accept-Encoding' }); // Return product data res.json(products);});
Performance Metrics:
- Cache Hit Ratio: 95%+ target
- Origin Load: Should be minimal
- Response Time: <100ms target
- Bandwidth Savings: 70%+ typical
Traffic Metrics:
- Requests per second
- Data transfer volume
- Geographic distribution
- Popular content analysis
Problem: Stale content served to users
Solution: Implement proper versioning and purging
2. Dynamic Content Caching
Problem: Caching user-specific data
Solution: Use proper cache headers and vary headers
3. Origin Server Overload
Problem: Cache miss storms during traffic spikes
Solution: Implement cache warming and proper TTLs
4. Geographic Routing Issues
Problem: Users routed to distant edge servers
Solution: Verify DNS configuration and CDN settings
Use Cases
1. E-commerce Websites
Product images and catalogs
Static CSS/JS files
Product recommendation APIs
Geographic price optimization
2. Media & Entertainment
Video streaming (Netflix, YouTube)
Image galleries (Instagram, Pinterest)
Audio streaming (Spotify, Apple Music)
Live event broadcasting
3. Gaming
Game asset downloads
(Not real-time multiplayer data: that goes to game servers, not the CDN)
Leaderboards and statistics
Mobile game content
4. SaaS Applications
Application assets
Documentation sites
API responses
User interface components
CDNs are essential for modern web applications, providing faster content delivery, improved user experience, and reduced server costs. Choose the right CDN provider based on your specific needs, budget, and geographic requirements.
AI-powered solutions for modern payment systems and financial services
Overview
FinTech companies like JusPay leverage embedding technologies and AI to enhance payment processing, fraud detection, customer support, and compliance. These systems handle millions of transactions daily with high accuracy and low latency.
Data Lake: Store transaction and user behavior data
Scalability Requirements (illustrative assumptions, not JusPay-published figures)
TPS: 10,000+ transactions per second
Latency: < 200ms for payment processing
Availability: 99.99% uptime
Data: Process 1TB+ daily transaction data
Interview Questions for SDE Intern
System Design Questions
Design a real-time fraud detection system for JusPay
Build a payment retry mechanism with smart routing
Create a customer support chatbot using RAG
Design a transaction reconciliation system
Build an anomaly detection pipeline for transactions
Technical Questions
How would you handle high-frequency trading scenarios?
Explain PCI DSS compliance in payment systems
How to ensure idempotency in payment APIs?
Design rate limiting for payment APIs
How to handle eventual consistency in distributed payments?
ML/AI Questions
How to detect concept drift in fraud models?
Explain feature importance in fraud detection
How to handle imbalanced datasets in fraud detection?
Design A/B testing for ML models in production
How to ensure model explainability for regulatory compliance?
This comprehensive guide covers the essential aspects of FinTech system design with a focus on AI/ML applications, specifically tailored for companies like JusPay and suitable for SDE Intern interviews.