Mikroservis patternlari

30.06.2026 | Muallif: Jaxongir a.k.a | Kategoriya: Microservice Architecture | 30 daqiqa o'qish

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 chaqiryapti

Bu 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 bor

2. Microservices’da asosiy muammo

Monolith’da chaqiriq oddiy:

paymentService.pay(order);

Hammasi bitta process ichida.

Microservice’da esa:

Order Service → network → Payment Service

Bu 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‘ladi

Shuning 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 Service

Bu yomon, chunki client hamma servicelarni bilib qoladi.

Gateway bilan:

Mobile App / Web App
        ↓
   API Gateway
        ↓
 ┌───────────────┬───────────────┬───────────────┐
 Order Service   User Service    Payment Service

Client 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 breaker

Masalan:

/api/orders/**  → order-service
/api/users/**   → user-service
/api/payments/** → payment-service

5. 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/15

Order service esa shuni kutadi:

GET /orders/15

Gateway’da rewrite qilish mumkin:

spring:
  cloud:
    gateway:
      routes:
        - id: order-service
          uri: http://order-service:8080
          predicates:
            - Path=/api/orders/**
          filters:
            - StripPrefix=1

StripPrefix=1 /api qismini olib tashlaydi.


7. Gateway’da auth

Gateway authenticationni markaziy joyda tekshirishi mumkin.

Masalan:

Client → Gateway → JWT tekshirildi → Order Service

Lekin muhim qoida:

Gateway tekshirgan bo‘lsa ham, ichki service’lar butunlay ishonchsiz bo‘lib qolmasligi kerak.

Yomon:

Gateway bor, demak service ichida security kerak emas

Bu xavfli.

To‘g‘ri:

Gateway umumiy auth tekshiradi
Service o‘z authorization/business permissionini tekshiradi

Masalan:

  • 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 request

Redis 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: 20

Bu 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 tekshiradi

Gateway biznes logic joyi emas.

Gateway vazifasi:

routing
security
rate limit
cross-cutting concerns

Business 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
Alerting

bo‘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 call

ishlatiladi.


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.9

Agar Payment Service Order Service IP’sini hardcode qilsa, tez buziladi.

Yomon:

order-service-url: http://10.1.1.5:8080

To‘g‘ri:

order-service-url: http://order-service

Service 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 chaqiradi

Misol texnologiyalar:

Netflix Eureka
Consul
Zookeeper

11.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-service

Kubernetes 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 topadi

Eureka 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/eureka

Lekin 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: 8080

Endi boshqa service ichidan:

http://order-service

deb chaqirish mumkin.

Agar namespace kerak bo‘lsa:

http://order-service.default.svc.cluster.local

Bu 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 emas

Muhim qoida:

Service’lar bir-birining database’iga to‘g‘ridan-to‘g‘ri ulanmasligi kerak.

Yomon:

Order Service → Payment DB

To‘g‘ri:

Order Service → Payment Service API

Yoki event orqali:

Payment Service → PaymentCompleted event → Order Service

15. 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 qulay

Kamchiliklari:

Text-based, gRPC’dan sekinroq bo‘lishi mumkin
Contract buzilishi oson
Network timeout/retry kerak
Versioning muammosi bor

Java’da REST client uchun:

RestClient
WebClient
OpenFeign

ishlatiladi.


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: 3000

Tushuntirish:

connectTimeout - ulanishga qancha kutadi
readTimeout - javobga qancha kutadi

Timeout 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 candidate

20. Feign + Resilience4j

Service-to-service communication’da quyidagilar kerak:

timeout
retry
circuit breaker
bulkhead
fallback
rate limit

Masalan:

@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 validation

22. gRPC nima?

gRPC - Google yaratgan high-performance RPC framework.

U odatda:

HTTP/2
Protocol Buffers
Strongly typed contract
Binary serialization
Streaming

asosida ishlaydi.

REST:

JSON + HTTP

gRPC:

Protobuf + HTTP/2

23. 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 bor

Masalan:

Order Service → Pricing Service
Order Service → Inventory Service
Recommendation Service → User Profile Service

Lekin 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 ← response

Eng 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 3

Misol:

Order status updates
Live notifications

27.3. Client streaming

Client ko‘p request yuboradi, server bitta response qaytaradi.

Client → chunk 1
Client → chunk 2
Client → chunk 3
Client ← result

Misol:

File upload
Batch import

27.4. Bidirectional streaming

Client ham, server ham oqim yuboradi.

Client ↔ Server

Misol:

Chat
Live collaboration
Real-time telemetry

28. 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

.proto majburiy

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/RabbitMQ

29. Sidecar pattern

Sidecar - asosiy app yonida alohida yordamchi container/process ishlashi.

Kubernetes pod ichida:

Pod
 ├── app container
 └── sidecar container

Sidecar appga yordam beradi, lekin biznes logicni bajarmaydi.

Misollar:

log collector
proxy
service mesh proxy
config reloader
security agent
file sync agent
metrics exporter

30. Sidecar real misol

App log yozadi:

/app/logs/app.log

Sidecar shu logni o‘qib tashqi tizimga yuboradi:

Pod
 ├── Java app
 └── Fluent Bit sidecar → Loki/Elasticsearch

Yoki service mesh’da:

Pod
 ├── Java app
 └── Envoy proxy

Barcha 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 markazlashadi

Masalan, 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 murakkablashadi

Senior 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
Kuma

Service mesh odatda sidecar proxy ishlatadi.

Architecture:

Service A app → Sidecar proxy → network → Sidecar proxy → Service B app

App 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 enforcement

Masalan, siz code o‘zgartirmasdan:

10% traffic → payment-service v2
90% traffic → payment-service v1

qila 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: 10

Bu canary deployment uchun ishlatiladi.


36. mTLS

mTLS - mutual TLS.

Oddiy TLS’da client serverni tekshiradi.

mTLS’da:

Client serverni tekshiradi
Server ham clientni tekshiradi

Microservice’da:

Order Service ↔ Payment Service

ikkalasi 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 kerak

Lekin 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 → Microservices

Nega kerak?

Mobile va web ehtiyoji har xil bo‘lishi mumkin.

Mobile:

Kamroq data
Kamroq request
Battery/network tejalishi kerak

Web:

Ko‘proq data
Katta ekran
Boshqa UI flow

BFF clientga mos response tayyorlaydi.


40. Aggregator pattern

Ba’zida clientga bitta response kerak, lekin data bir nechta servicedan keladi.

GET /checkout-summary

Kerakli data:

User Service
Cart Service
Bonus Service
Payment Method Service

Aggregator:

Client → Checkout Aggregator → User/Cart/Bonus/Payment services

Java 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 900ms

Yaxshi:

Uchalasini parallel chaqirish
Total taxminan 300ms

Xato 3: Timeout/fallback yo‘q

Bitta optional service sekinlashsa, butun response sekinlashadi.

Masalan bonus service ishlamasa, checkout summary baribir qaytishi mumkin:

bonus = 0

42. 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 Microservice

Masalan:

/orders eski monolithda
/payments yangi payment-service’da
/users hali monolithda

Vaqt 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 DB

Yomon:

Order Service → Payment DBga JOIN qiladi

Bu service boundary’ni buzadi.

Lekin database per service qilinsa:

JOIN qilish qiyinlashadi
Transaction murakkablashadi
Eventual consistency paydo bo‘ladi
Reporting qiyinlashadi

Yechimlar:

API composition
CQRS/read model
Event-driven sync
Outbox pattern
Data warehouse/reporting pipeline

44. 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 classes

Yomon shared library:

business logic
entity classes
repository
service layer
domain rules

Agar 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/orders

Yoki header orqali:

Accept: application/vnd.company.orders.v2+json

Event 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 eziladi

Bu retry storm.

To‘g‘ri:

Qisqa timeout
Limitlangan retry
Exponential backoff
Circuit breaker
Idempotency
Fallback

47. 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 pool

Payment sekinlashsa, faqat payment pool to‘ladi. Inventory ham bloklanib qolmaydi.

Resilience4j bulkhead konsepti:

resilience4j:
  bulkhead:
    instances:
      paymentService:
        maxConcurrentCalls: 20
        maxWaitDuration: 100ms

48. 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 latency

Bitta request flow:

Gateway → Order → Payment → Inventory

Trace’da shunday ko‘rinishi kerak:

Gateway: 20ms
Order Service: 80ms
Payment Service: 600ms
Inventory Service: 40ms

Shunda 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 management

Masalan 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 token

50. 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 Service

Patternlar:

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 uchun

Checkout 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 yuboradi

Muhim:

Payment idempotency key bilan
Inventory consistency ehtiyotkorlik bilan
Notification eventual consistency
Order eventlari outbox orqali
TraceId hamma service bo‘ylab yuradi

52. 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:8083

Gateway yozing:

/api/orders/**   → order-service
/api/users/**    → user-service
/api/payments/** → payment-service

Talab:

StripPrefix ishlating
Correlation ID qo‘shing
Basic logging qo‘shing

Topshiriq 2: OpenFeign

Order Service ichidan Payment Service chaqiring.

Talab:

Feign client
connectTimeout/readTimeout
custom error decoder
fallback yoki circuit breaker

Topshiriq 3: gRPC

Payment Service uchun .proto yozing:

Pay
GetPayment

Java server va client yozing.

Talab:

Unary RPC
status field
error handling

Topshiriq 4: Service discovery

Kubernetes’da:

order-service
payment-service

Deployment va Service yozing. Payment Service ichidan:

http://order-service

orqali Order Service’ni chaqiring.


Topshiriq 5: Aggregator

Checkout Summary endpoint yozing:

GET /checkout-summary/{userId}

U quyidagilarni chaqirsin:

user-service
cart-service
bonus-service

Talab:

Parallel call
Timeout
Fallback
Trace/correlation ID propagation

55. 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 ownership

Eng 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.