Overview
The service handles inventory initialization, stock adjustments, reservations for orders, and automatic reservation expiration. It uses PostgreSQL for persistent storage and Redis for caching and reservation TTL management.The Inventory service runs on port 8080 by default and requires both PostgreSQL and Redis.
Technology stack
- Language: Go 1.23
- Framework: Gin 1.10.0
- Database: PostgreSQL (pgx/v5)
- Cache: Redis (go-redis/v9)
- Key packages:
github.com/gin-gonic/gin- HTTP frameworkgithub.com/jackc/pgx/v5- PostgreSQL drivergithub.com/redis/go-redis/v9- Redis clientgithub.com/google/uuid- UUID generation
Configuration
Environment variables
Server port
Gin mode (debug, release)
Database configuration
PostgreSQL connection stringExample:
postgres://postgres:postgres@localhost:5432/inventory?sslmode=disableRedis configuration
Redis server address
Redis password (if required)
Redis database number
Reservation configuration
Reservation time-to-live (e.g., 10m, 1h)
How often to check for expired reservations
API endpoints
Health check
Initialize inventory
Get inventory
Add stock
Reserve stock
Reservations automatically expire after the configured
RESERVATION_TTL and return stock to available inventory.Release reservation
Deduct reservation
Deducting a reservation permanently removes the quantity from inventory when an order is confirmed.
Data models
InventoryStock
InventoryReservation
Reservation workflow
- Reserve: Create a reservation when a user adds items to cart/starts checkout
- Deduct: Finalize the reservation when payment is confirmed
- Release: Cancel the reservation if the user abandons the cart or payment fails
- Auto-expire: System automatically releases reservations after TTL expires
Error responses
Running the service
Database migrations
The service automatically runs migrations on startup from themigrations/ directory.
Background workers
The service runs a background worker that periodically checks for expired reservations and releases them:Performance considerations
- Redis caching: Frequently accessed inventory data is cached in Redis
- Connection pooling: PostgreSQL connections are pooled via pgxpool
- Atomic operations: Stock updates use database transactions for consistency
- Structured logging: JSON logs for production observability
Dependencies
- PostgreSQL: For persistent inventory storage
- Redis: For caching and reservation expiration tracking
- Product service: For product ID validation (optional)
Source code
Location:~/workspace/source/micros/inventory-service/
Key files:
cmd/main.go- Application entry pointinternal/handlers/inventory_handler.go- HTTP handlersinternal/services/inventory_service.go- Business logicinternal/repository/inventory_repository.go- Database operationsinternal/routes/routes.go- Route definitionsinternal/config/config.go- Configurationinternal/models/inventory.go- Data models