Microservices patterns ichiga quyidagilar kiradi: API Gateway, Service Discovery, gRPC with Java, OpenFeign declarative HTTP clients, Sidecar va Service Mesh concepts.
1. Microservices patterns nima?
Microservices patterns - microservice arxitekturasida servislar bir-biri bilan qanday gaplashadi, qanday topiladi, qanday himoyalanadi, qanday monitoring qilinadi va qanday boshqariladi - shular uchun ishlatiladigan tayyor yechimlar.
Microservice faqat appni bo‘lib tashlash emas.
Yomon yondashuv:
Monolith bor edi
Uni 10 ta servicega bo‘ldik
Endi hammasi REST bilan bir-birini chaqiryaptiBu microservice emas, bu distributed monolith bo‘lishi mumkin.
Yaxshi microservice design:
Har service o‘z mas’uliyatiga ega
Har service mustaqil deploy qilinadi
Service’lar aniq contract orqali gaplashadi
Failure holatlar hisobga olinadi
Observability bor
Security bor
Gateway bor
Service discovery bor2. Microservices’da asosiy muammo
Monolith’da chaqiriq oddiy:
paymentService.pay(order);Hammasi bitta process ichida.
Microservice’da esa:
Order Service → network → Payment ServiceBu yerda muammolar ko‘payadi:
Payment Service down bo‘lishi mumkin
Network timeout bo‘lishi mumkin
Service IP o‘zgarishi mumkin
Request duplicate ketishi mumkin
Response sekin kelishi mumkin
Security kerak bo‘ladi
Tracing kerak bo‘ladiShuning uchun microservices patterns kerak.
3. API Gateway
API Gateway - clientlar bilan backend microservicelar orasidagi kirish nuqtasi.
Oddiy holat:
Mobile App → Order Service
Mobile App → Payment Service
Mobile App → User Service
Mobile App → Notification ServiceBu yomon, chunki client hamma servicelarni bilib qoladi.
Gateway bilan:
Mobile App / Web App
↓
API Gateway
↓
┌───────────────┬───────────────┬───────────────┐
Order Service User Service Payment ServiceClient faqat gateway’ni biladi.
4. API Gateway nima qiladi?
API Gateway odatda quyidagilarni bajaradi:
Routing
Authentication check
Authorization check
Rate limiting
Request/response transformation
CORS
SSL termination
Logging
Tracing
Load balancing
Circuit breakerMasalan:
/api/orders/** → order-service
/api/users/** → user-service
/api/payments/** → payment-service5. Spring Cloud Gateway
Java/Spring ekotizimida gateway uchun ko‘p ishlatiladigan variantlardan biri - Spring Cloud Gateway.
U WebFlux/Reactor ustida ishlaydi, ya’ni non-blocking.
Minimal dependency:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway-server-webflux</artifactId>
</dependency>Oddiy config:
spring:
cloud:
gateway:
routes:
- id: order-service
uri: http://order-service:8080
predicates:
- Path=/api/orders/**
- id: user-service
uri: http://user-service:8080
predicates:
- Path=/api/users/**
- id: payment-service
uri: http://payment-service:8080
predicates:
- Path=/api/payments/**Bu yerda gateway request path bo‘yicha service’ga yo‘naltiradi.
6. Gateway path rewrite
Ko‘p holatda tashqi path bilan ichki service path farq qiladi.
Tashqi request:
GET /api/orders/15Order service esa shuni kutadi:
GET /orders/15Gateway’da rewrite qilish mumkin:
spring:
cloud:
gateway:
routes:
- id: order-service
uri: http://order-service:8080
predicates:
- Path=/api/orders/**
filters:
- StripPrefix=1StripPrefix=1 /api qismini olib tashlaydi.
7. Gateway’da auth
Gateway authenticationni markaziy joyda tekshirishi mumkin.
Masalan:
Client → Gateway → JWT tekshirildi → Order ServiceLekin muhim qoida:
Gateway tekshirgan bo‘lsa ham, ichki service’lar butunlay ishonchsiz bo‘lib qolmasligi kerak.
Yomon:
Gateway bor, demak service ichida security kerak emasBu xavfli.
To‘g‘ri:
Gateway umumiy auth tekshiradi
Service o‘z authorization/business permissionini tekshiradiMasalan:
Gateway token borligini tekshiradi;
Order Service user faqat o‘z orderini ko‘rayotganini tekshiradi.
8. Gateway rate limiting
Gateway rate limiting uchun yaxshi joy.
Masalan:
1 user → 1 minutda 100 request
1 IP → 1 minutda 500 request
1 API key → 1 sekundda 20 requestRedis bilan rate limiter konsepti:
spring:
cloud:
gateway:
routes:
- id: order-service
uri: http://order-service:8080
predicates:
- Path=/api/orders/**
filters:
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20Bu abuse, bot, DDoS yoki xato clientlardan himoya qiladi.
9. API Gateway xatolari
Xato 1: Gateway ichiga business logic yozish
Yomon:
Gateway order narxini hisoblaydi
Gateway bonus qo‘shadi
Gateway inventory tekshiradiGateway biznes logic joyi emas.
Gateway vazifasi:
routing
security
rate limit
cross-cutting concernsBusiness logic esa service ichida bo‘lishi kerak.
Xato 2: Gateway single point of failure bo‘lishi
Gateway yiqilsa, hamma API yiqiladi.
Shuning uchun:
Gateway kamida 2+ replica
Load balancer ortida
Health check
Autoscaling
Metrics
Alertingbo‘lishi kerak.
Xato 3: Har narsani gateway orqali o‘tkazish
Ichki service-to-service communication har doim gateway orqali bo‘lishi shart emas.
Ko‘pincha:
External client → Gateway → Service
Internal service → Service Discovery / direct service callishlatiladi.
10. Service Discovery
Microservice’da service IP doimiy emas.
Kubernetes’da podlar o‘chadi, yangisi chiqadi:
order-service pod old IP: 10.1.1.5
order-service pod new IP: 10.1.2.9Agar Payment Service Order Service IP’sini hardcode qilsa, tez buziladi.
Yomon:
order-service-url: http://10.1.1.5:8080To‘g‘ri:
order-service-url: http://order-serviceService Discovery - service’lar bir-birini nomi orqali topishi.
11. Service Discovery turlari
11.1. Client-side discovery
Client registry’dan service manzilini oladi.
Payment Service
↓
Service Registry’dan order-service instances so‘raydi
↓
Bittasini tanlab chaqiradiMisol texnologiyalar:
Netflix Eureka
Consul
Zookeeper11.2. Server-side discovery
Client oddiy service nomiga request qiladi. Load balancing va routing platforma tomonidan bajariladi.
Kubernetes’da odatda shu model:
Payment Service → http://order-serviceKubernetes Service DNS orqali kerakli podlarga yo‘naltiradi.
12. Eureka
Spring Cloud eski microservice stacklarida Eureka ko‘p ishlatilgan.
Architecture:
Order Service → Eureka’ga register bo‘ladi
Payment Service → Eureka’dan Order Service’ni topadiEureka server:
@EnableEurekaServer
@SpringBootApplication
public class DiscoveryServerApplication {
public static void main(String[] args) {
SpringApplication.run(DiscoveryServerApplication.class, args);
}
}Service client:
spring:
application:
name: order-service
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eurekaLekin Kubernetes ishlatilsa, ko‘pincha alohida Eureka kerak bo‘lmaydi. Kubernetes DNS va Service mexanizmi yetarli bo‘ladi.
13. Kubernetes service discovery
Kubernetes’da Service yaratamiz:
apiVersion: v1
kind: Service
metadata:
name: order-service
spec:
selector:
app: order-service
ports:
- port: 80
targetPort: 8080Endi boshqa service ichidan:
http://order-servicedeb chaqirish mumkin.
Agar namespace kerak bo‘lsa:
http://order-service.default.svc.cluster.localBu Kubernetes native service discovery.
14. Service-to-service communication
Microservicelar bir-biri bilan bir necha yo‘l orqali gaplashadi:
REST/HTTP
gRPC
Messaging: Kafka/RabbitMQ
GraphQL federation
Database orqali emasMuhim qoida:
Service’lar bir-birining database’iga to‘g‘ridan-to‘g‘ri ulanmasligi kerak.
Yomon:
Order Service → Payment DBTo‘g‘ri:
Order Service → Payment Service APIYoki event orqali:
Payment Service → PaymentCompleted event → Order Service15. REST communication
REST eng ko‘p ishlatiladigan model.
Afzalliklari:
Tushunish oson
HTTP asosida
Debug qilish oson
Browser/Postman/curl bilan test qilish oson
JSON bilan qulayKamchiliklari:
Text-based, gRPC’dan sekinroq bo‘lishi mumkin
Contract buzilishi oson
Network timeout/retry kerak
Versioning muammosi borJava’da REST client uchun:
RestClient
WebClient
OpenFeignishlatiladi.
16. OpenFeign
OpenFeign - declarative HTTP client.
Ya’ni siz interface yozasiz, Spring o‘zi HTTP client implementation yaratadi.
Dependency:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>Enable qilish:
@EnableFeignClients
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}17. Feign client misol
Payment Service chaqirish:
@FeignClient(
name = "payment-service",
url = "${services.payment.url}"
)
public interface PaymentClient {
@PostMapping("/payments")
PaymentResponse pay(@RequestBody PaymentRequest request);
@GetMapping("/payments/{id}")
PaymentResponse getPayment(@PathVariable Long id);
}Service’da ishlatish:
@Service
@RequiredArgsConstructor
public class CheckoutService {
private final PaymentClient paymentClient;
public CheckoutResponse checkout(CheckoutRequest request) {
PaymentResponse payment = paymentClient.pay(
new PaymentRequest(request.orderId(), request.amount())
);
return new CheckoutResponse(payment.status());
}
}Bu juda qulay, lekin timeout, retry, error handling sozlanmasa productionda xavfli.
18. Feign timeout config
Feign clientda timeout shart.
spring:
cloud:
openfeign:
client:
config:
payment-service:
connectTimeout: 1000
readTimeout: 3000Tushuntirish:
connectTimeout - ulanishga qancha kutadi
readTimeout - javobga qancha kutadiTimeout yo‘q bo‘lsa, thread uzoq osilib qolishi mumkin.
19. Feign error handling
Payment service 400, 404, 500 qaytarishi mumkin.
Custom error decoder:
@Component
public class FeignErrorDecoder implements ErrorDecoder {
private final ErrorDecoder defaultDecoder = new Default();
@Override
public Exception decode(String methodKey, Response response) {
if (response.status() == 404) {
return new PaymentNotFoundException("Payment not found");
}
if (response.status() >= 500) {
return new PaymentServiceUnavailableException("Payment service error");
}
return defaultDecoder.decode(methodKey, response);
}
}Senior yondashuv:
4xx - client/business error sifatida ko‘riladi
5xx - retry/circuit breaker candidate
timeout - fallback/circuit breaker candidate20. Feign + Resilience4j
Service-to-service communication’da quyidagilar kerak:
timeout
retry
circuit breaker
bulkhead
fallback
rate limitMasalan:
@CircuitBreaker(name = "paymentService", fallbackMethod = "paymentFallback")
public CheckoutResponse checkout(CheckoutRequest request) {
PaymentResponse payment = paymentClient.pay(
new PaymentRequest(request.orderId(), request.amount())
);
return new CheckoutResponse(payment.status());
}
public CheckoutResponse paymentFallback(CheckoutRequest request, Throwable ex) {
return new CheckoutResponse("PAYMENT_TEMPORARILY_UNAVAILABLE");
}Bu Payment Service down bo‘lsa, Order Service ham yiqilmasligi uchun kerak.
21. REST contract muammosi
Microservice’da contract buzilishi juda xavfli.
Payment Service response’ni o‘zgartirdi:
Oldin:
{
"status": "SUCCESS"
}Keyin:
{
"paymentStatus": "SUCCESS"
}Order Service eski fieldni kutayotgan bo‘lsa, productionda xato bo‘ladi.
Yechimlar:
OpenAPI contract
Consumer-driven contract testing
Backward compatibility
Versioning
Schema validation22. gRPC nima?
gRPC - Google yaratgan high-performance RPC framework.
U odatda:
HTTP/2
Protocol Buffers
Strongly typed contract
Binary serialization
Streamingasosida ishlaydi.
REST:
JSON + HTTPgRPC:
Protobuf + HTTP/223. gRPC qachon foydali?
gRPC yaxshi tanlov bo‘lishi mumkin, agar:
Internal service-to-service communication kerak
Low latency muhim
High throughput kerak
Strong contract kerak
Streaming kerak
Polyglot microservice borMasalan:
Order Service → Pricing Service
Order Service → Inventory Service
Recommendation Service → User Profile ServiceLekin public browser API uchun REST ko‘pincha qulayroq. Browser/gRPC-web alohida murakkablik olib keladi.
24. Protobuf contract
gRPC’da avval .proto file yoziladi.
syntax = "proto3";
package payment;
option java_package = "uz.example.payment.grpc";
option java_multiple_files = true;
service PaymentService {
rpc Pay(PaymentRequest) returns (PaymentResponse);
rpc GetPayment(GetPaymentRequest) returns (PaymentResponse);
}
message PaymentRequest {
string order_id = 1;
int64 amount = 2;
string currency = 3;
}
message GetPaymentRequest {
string payment_id = 1;
}
message PaymentResponse {
string payment_id = 1;
string status = 2;
}Bu contractdan Java classlar generatsiya qilinadi.
25. gRPC server Java misol
@GrpcService
public class PaymentGrpcService extends PaymentServiceGrpc.PaymentServiceImplBase {
@Override
public void pay(PaymentRequest request,
StreamObserver<PaymentResponse> responseObserver) {
PaymentResponse response = PaymentResponse.newBuilder()
.setPaymentId(UUID.randomUUID().toString())
.setStatus("SUCCESS")
.build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}gRPC’da response StreamObserver orqali yuboriladi.
26. gRPC client Java misol
@Service
@RequiredArgsConstructor
public class PaymentGrpcClient {
private final PaymentServiceGrpc.PaymentServiceBlockingStub paymentStub;
public PaymentResponse pay(String orderId, long amount, String currency) {
PaymentRequest request = PaymentRequest.newBuilder()
.setOrderId(orderId)
.setAmount(amount)
.setCurrency(currency)
.build();
return paymentStub.pay(request);
}
}Blocking stub ishlatilsa, u ham blocking call bo‘ladi. Async stub ham bor.
27. gRPC turlari
gRPC 4 xil communication model beradi:
27.1. Unary
Bitta request, bitta response.
Client → request
Client ← responseEng oddiy va ko‘p ishlatiladi.
27.2. Server streaming
Client bitta request yuboradi, server ko‘p response yuboradi.
Client → request
Client ← response 1
Client ← response 2
Client ← response 3Misol:
Order status updates
Live notifications27.3. Client streaming
Client ko‘p request yuboradi, server bitta response qaytaradi.
Client → chunk 1
Client → chunk 2
Client → chunk 3
Client ← resultMisol:
File upload
Batch import27.4. Bidirectional streaming
Client ham, server ham oqim yuboradi.
Client ↔ ServerMisol:
Chat
Live collaboration
Real-time telemetry28. REST vs gRPC
Mezon | REST | gRPC |
|---|---|---|
Format | JSON | Protobuf |
Protocol | HTTP/1.1 yoki HTTP/2 | HTTP/2 |
O‘qilishi | Odamga oson | Binary, odamga qiyin |
Browser support | Juda yaxshi | gRPC-web kerak |
Contract | OpenAPI bilan |
|
Performance | Yaxshi | Juda yaxshi |
Streaming | Cheklangan/SSE/WebSocket | Native |
Debug | curl/Postman oson | grpcurl/tool kerak |
Public API | Juda mos | Kamroq mos |
Internal API | Mos | Juda mos |
Qisqa qoida:
Public API → REST
Internal high-performance service call → gRPC
Event async communication → Kafka/RabbitMQ29. Sidecar pattern
Sidecar - asosiy app yonida alohida yordamchi container/process ishlashi.
Kubernetes pod ichida:
Pod
├── app container
└── sidecar containerSidecar appga yordam beradi, lekin biznes logicni bajarmaydi.
Misollar:
log collector
proxy
service mesh proxy
config reloader
security agent
file sync agent
metrics exporter30. Sidecar real misol
App log yozadi:
/app/logs/app.logSidecar shu logni o‘qib tashqi tizimga yuboradi:
Pod
├── Java app
└── Fluent Bit sidecar → Loki/ElasticsearchYoki service mesh’da:
Pod
├── Java app
└── Envoy proxyBarcha network traffic Envoy orqali o‘tadi.
31. Sidecar afzalliklari
Cross-cutting concern appdan ajratiladi
Har service ichiga bir xil kod yozilmaydi
Tilga bog‘liq emas
Security/tracing/retry/proxy markazlashadiMasalan, 10 ta service bor. Har biriga mTLS, retry, metric kodini yozish o‘rniga sidecar proxy orqali boshqarish mumkin.
32. Sidecar kamchiliklari
Resource ko‘proq yeydi
Pod murakkablashadi
Debug qiyinlashadi
Network path uzayadi
Latency biroz oshishi mumkin
Config murakkablashadiSenior developer sidecar qo‘shishdan oldin trade-offni tushunishi kerak.
33. Service Mesh
Service Mesh - microservicelar orasidagi network communicationni boshqaradigan infrastructure layer.
Mashhur service meshlar:
Istio
Linkerd
Consul Connect
KumaService mesh odatda sidecar proxy ishlatadi.
Architecture:
Service A app → Sidecar proxy → network → Sidecar proxy → Service B appApp service mesh borligini bilmasligi ham mumkin.
34. Service Mesh nima beradi?
Service mesh quyidagilarni beradi:
mTLS service-to-service encryption
Traffic routing
Canary deployment
Retries
Timeouts
Circuit breaking
Load balancing
Observability
Distributed tracing
Policy enforcementMasalan, siz code o‘zgartirmasdan:
10% traffic → payment-service v2
90% traffic → payment-service v1qila olasiz.
35. Istio misol: traffic split
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: payment-service
spec:
hosts:
- payment-service
http:
- route:
- destination:
host: payment-service
subset: v1
weight: 90
- destination:
host: payment-service
subset: v2
weight: 10Bu canary deployment uchun ishlatiladi.
36. mTLS
mTLS - mutual TLS.
Oddiy TLS’da client serverni tekshiradi.
mTLS’da:
Client serverni tekshiradi
Server ham clientni tekshiradiMicroservice’da:
Order Service ↔ Payment Serviceikkalasi ham bir-birining identity’sini tekshiradi.
Service mesh mTLS’ni app kodiga kamroq tegib yoqib bera oladi.
37. Service Mesh qachon kerak?
Service mesh foydali bo‘lishi mumkin, agar:
Microservice soni ko‘p
Service-to-service traffic murakkab
mTLS kerak
Canary/traffic routing kerak
Platform team bor
Observability markazlashishi kerak
Policy kerakLekin 3-4 ta kichik service uchun Istio qo‘yish ortiqcha bo‘lishi mumkin.
38. Service Mesh xatolari
Xato 1: Juda erta qo‘shish
Agar tizim kichik bo‘lsa, service mesh operational complexityni oshiradi.
Xato 2: App muammosini mesh bilan yashirish
Noto‘g‘ri timeout, yomon retry, idempotency yo‘q - bularni mesh to‘liq hal qilib bermaydi.
Xato 3: Observabilitysiz ishlatish
Mesh qo‘shildi, lekin metrics/tracing qaralmaydi. Unda foydasi kam.
39. Backend for Frontend - BFF pattern
BFF - Backend for Frontend - har frontend turi uchun alohida backend layer.
Masalan:
Mobile App → Mobile BFF → Microservices
Web App → Web BFF → Microservices
Admin Panel → Admin BFF → MicroservicesNega kerak?
Mobile va web ehtiyoji har xil bo‘lishi mumkin.
Mobile:
Kamroq data
Kamroq request
Battery/network tejalishi kerakWeb:
Ko‘proq data
Katta ekran
Boshqa UI flowBFF clientga mos response tayyorlaydi.
40. Aggregator pattern
Ba’zida clientga bitta response kerak, lekin data bir nechta servicedan keladi.
GET /checkout-summaryKerakli data:
User Service
Cart Service
Bonus Service
Payment Method ServiceAggregator:
Client → Checkout Aggregator → User/Cart/Bonus/Payment servicesJava misol:
public CheckoutSummary getSummary(Long userId) {
UserDto user = userClient.getUser(userId);
CartDto cart = cartClient.getCart(userId);
BonusDto bonus = bonusClient.getBonus(userId);
return new CheckoutSummary(user, cart, bonus);
}Reactive/WebClient bilan parallel qilish mumkin:
public Mono<CheckoutSummary> getSummary(Long userId) {
Mono<UserDto> user = userClient.getUser(userId);
Mono<CartDto> cart = cartClient.getCart(userId);
Mono<BonusDto> bonus = bonusClient.getBonus(userId);
return Mono.zip(user, cart, bonus)
.map(t -> new CheckoutSummary(t.getT1(), t.getT2(), t.getT3()));
}41. Aggregator xatolari
Xato 1: Aggregator juda katta bo‘lib ketishi
Agar hamma business logic aggregatorga yig‘ilsa, u yangi monolith bo‘lib qoladi.
Xato 2: Sequential call
Yomon:
User call 300ms
Cart call 300ms
Bonus call 300ms
Total 900msYaxshi:
Uchalasini parallel chaqirish
Total taxminan 300msXato 3: Timeout/fallback yo‘q
Bitta optional service sekinlashsa, butun response sekinlashadi.
Masalan bonus service ishlamasa, checkout summary baribir qaytishi mumkin:
bonus = 042. Strangler Fig pattern
Strangler Fig - eski monolithni birdan buzib tashlamasdan, asta-sekin microservicega ko‘chirish patterni.
Flow:
Client → Gateway
├── eski endpointlar → Monolith
└── yangi endpointlar → New MicroserviceMasalan:
/orders eski monolithda
/payments yangi payment-service’da
/users hali monolithdaVaqt o‘tib service’lar monolithdan ajratiladi.
Bu migration uchun xavfsizroq.
43. Database per service pattern
Microservice’da har service o‘z data’siga egalik qilishi kerak.
Order Service → Order DB
Payment Service → Payment DB
Inventory Service → Inventory DBYomon:
Order Service → Payment DBga JOIN qiladiBu service boundary’ni buzadi.
Lekin database per service qilinsa:
JOIN qilish qiyinlashadi
Transaction murakkablashadi
Eventual consistency paydo bo‘ladi
Reporting qiyinlashadiYechimlar:
API composition
CQRS/read model
Event-driven sync
Outbox pattern
Data warehouse/reporting pipeline44. Shared library pattern
Microservicelar orasida shared library ishlatish mumkin, lekin ehtiyot bo‘lish kerak.
Yaxshi shared library:
common error model
logging helper
security utility
OpenAPI generated client
protobuf generated classesYomon shared library:
business logic
entity classes
repository
service layer
domain rulesAgar hamma service bitta common business libraryga bog‘lansa, mustaqil deploy qilish qiyinlashadi.
45. Versioning
Microservice contract o‘zgarsa, clientlar buzilmasligi kerak.
REST API version:
/api/v1/orders
/api/v2/ordersYoki header orqali:
Accept: application/vnd.company.orders.v2+jsonEvent version:
{
"eventType": "OrderCreated",
"schemaVersion": 2,
"orderId": 15
}Protobuf’da field numberlar muhim:
message PaymentResponse {
string payment_id = 1;
string status = 2;
}Eski field numberni qayta boshqa ma’noda ishlatish xavfli.
46. Timeout, retry, circuit breaker
Microservices’da bu uchlik majburiy.
Timeout
Qancha kutamiz?Retry
Vaqtinchalik xatoda qayta urinamizmi?Circuit breaker
Service yiqilgan bo‘lsa, uni yana ezmaymizmi?Yomon holat:
Payment Service sekin
Order Service 10 sekund kutadi
Client retry qiladi
Gateway retry qiladi
Order Service retry qiladi
Payment Service butunlay eziladiBu retry storm.
To‘g‘ri:
Qisqa timeout
Limitlangan retry
Exponential backoff
Circuit breaker
Idempotency
Fallback47. Bulkhead pattern
Bulkhead - bitta dependency muammosi butun serviceni yiqitmasligi uchun resurslarni ajratish.
Masalan Order Service ichida:
Payment client thread pool
Inventory client thread pool
Notification client thread poolPayment sekinlashsa, faqat payment pool to‘ladi. Inventory ham bloklanib qolmaydi.
Resilience4j bulkhead konsepti:
resilience4j:
bulkhead:
instances:
paymentService:
maxConcurrentCalls: 20
maxWaitDuration: 100ms48. Microservices observability
Microservice’da observability majburiy.
Kerak:
Correlation ID
Trace ID
Structured logs
Metrics
Distributed tracing
Service dependency graph
Gateway metrics
Client latency metrics
Error rate
p95/p99 latencyBitta request flow:
Gateway → Order → Payment → InventoryTrace’da shunday ko‘rinishi kerak:
Gateway: 20ms
Order Service: 80ms
Payment Service: 600ms
Inventory Service: 40msShunda bottleneck topiladi.
49. Microservices security
Service-to-service security ham muhim.
Kerak bo‘lishi mumkin:
JWT propagation
OAuth2 client credentials
mTLS
Network policy
API gateway auth
Service-level authorization
Secret managementMasalan external user tokenini hamma service’ga uzatish har doim to‘g‘ri emas.
Ba’zan ichki service call uchun alohida service token ishlatiladi:
Order Service → Payment Service
Client credentials token50. Senior checklist
Microservice pattern tanlashdan oldin tekshir:
Gateway kerakmi?
Service discovery qanday bo‘ladi?
REST, gRPC yoki messaging tanlanadimi?
Timeoutlar sozlanganmi?
Retry idempotent operationlargami?
Circuit breaker bormi?
Service contract versionlanadimi?
Observability bormi?
Service-to-service auth bormi?
Database boundary aniqmi?
Shared library haddan oshmaganmi?
Deployment mustaqilmi?
Failure holatlar design qilinganmi?51. Real ecommerce microservice design
Masalan ecommerce tizim:
Client
↓
API Gateway
↓
Order Service
Payment Service
Inventory Service
User Service
Notification ServicePatternlar:
API Gateway → tashqi requestlar uchun
Kubernetes Service Discovery → ichki service topish uchun
OpenFeign/WebClient → REST clientlar
Kafka → async eventlar
Outbox → event yo‘qolmasligi uchun
Circuit Breaker → tashqi dependency himoyasi
BFF → mobile/web farqli response uchun
Service Mesh → mTLS/canary/traffic policy uchunCheckout flow:
1. Client → Gateway → Order Service
2. Order Service paymentni chaqiradi yoki event chiqaradi
3. Payment Service payment qiladi
4. Inventory Service stock reserve qiladi
5. Notification Service event orqali xabar yuboradiMuhim:
Payment idempotency key bilan
Inventory consistency ehtiyotkorlik bilan
Notification eventual consistency
Order eventlari outbox orqali
TraceId hamma service bo‘ylab yuradi52. Senior xatolari
Xato 1: Monolithni bevaqt microservice qilish
Agar domain aniq bo‘lmasa, microservice faqat murakkablikni oshiradi.
Xato 2: Service’lar DB ulashib ishlashi
Bu mustaqillikni buzadi.
Xato 3: Timeout yo‘q
Bitta service sekinlashsa, butun tizim osilib qoladi.
Xato 4: Retry noto‘g‘ri
Retry storm hosil bo‘ladi.
Xato 5: Gatewayga business logic yozish
Gateway yangi monolithga aylanadi.
Xato 6: Observabilitysiz microservice
Muammo qayerda ekanini topib bo‘lmaydi.
Xato 7: Shared library orqali kuchli coupling
Service’lar mustaqil deploy bo‘lmay qoladi.
Xato 8: gRPC/Service Meshni moda uchun qo‘shish
Har texnologiya aniq muammo uchun tanlanishi kerak.
53. Interview savollari
API Gateway
API Gateway nima qiladi?
Gateway bilan Load Balancer farqi nima?
Gateway ichiga business logic yozish nega yomon?
Gateway single point of failure bo‘lmasligi uchun nima qilasiz?
Service Discovery
Service discovery nima?
Eureka va Kubernetes Service farqi nima?
Client-side va server-side discovery farqi?
OpenFeign / REST
OpenFeign nima?
Feign’da timeout qayerda sozlanadi?
Feign error decoder nima?
REST contract buzilmasligi uchun nima qilasiz?
gRPC
gRPC nima?
REST va gRPC farqi?
Protobuf field number nima uchun muhim?
gRPC streaming turlari qanday?
Sidecar / Service Mesh
Sidecar pattern nima?
Service mesh nima beradi?
Istio/Linkerd qachon kerak?
mTLS nima?
Architecture
Database per service nima?
BFF pattern nima?
Aggregator pattern xatolari?
Strangler Fig pattern nima?
Distributed monolith nima?
54. Amaliy topshiriqlar
Topshiriq 1: API Gateway
3 ta service tasavvur qiling:
order-service:8081
user-service:8082
payment-service:8083Gateway yozing:
/api/orders/** → order-service
/api/users/** → user-service
/api/payments/** → payment-serviceTalab:
StripPrefix ishlating
Correlation ID qo‘shing
Basic logging qo‘shingTopshiriq 2: OpenFeign
Order Service ichidan Payment Service chaqiring.
Talab:
Feign client
connectTimeout/readTimeout
custom error decoder
fallback yoki circuit breakerTopshiriq 3: gRPC
Payment Service uchun .proto yozing:
Pay
GetPaymentJava server va client yozing.
Talab:
Unary RPC
status field
error handlingTopshiriq 4: Service discovery
Kubernetes’da:
order-service
payment-serviceDeployment va Service yozing. Payment Service ichidan:
http://order-serviceorqali Order Service’ni chaqiring.
Topshiriq 5: Aggregator
Checkout Summary endpoint yozing:
GET /checkout-summary/{userId}U quyidagilarni chaqirsin:
user-service
cart-service
bonus-serviceTalab:
Parallel call
Timeout
Fallback
Trace/correlation ID propagation55. Qisqa xulosa
Microservices patterns Senior Java developer uchun juda muhim production mavzu.
Asosiy fikrlar:
API Gateway - tashqi trafik kirish nuqtasi
Service Discovery - service’larni nomi orqali topish
OpenFeign - declarative REST client
gRPC - tez, contract-first internal communication
Sidecar - app yonidagi yordamchi container
Service Mesh - service-to-service trafficni boshqarish layeri
BFF - frontendga mos backend layer
Aggregator - bir nechta service datalarini yig‘ish
Strangler Fig - monolithdan bosqichma-bosqich chiqish
Database per service - service data ownershipEng muhim qoida:
Microservice patternlar texnologiya tanlash emas, failure, coupling, scalability, security va observability muammolarini to‘g‘ri boshqarish uchun ishlatiladi. Microservice qilishdan oldin "nima yutamiz va nima murakkablashadi?" degan savolga aniq javob bo‘lishi kerak.