This service exposes two APIs:
- Create user:
POST /api/v1/userswithname, email, password, age? - Create order:
POST /api/v1/orderswithuser_id, item, category, price
When an order is created, a background job analyzes and stores the user's interests using OpenAI.
users: core user profile, includesagefor personalizationorders: normalized orders table with indexes on(user_id, category)user_interests: 1:1 with user, containssummaryandproperties(JSON)
- Controller: thin HTTP entry points
- Request: validation layer
- Resource: response mapping
- Service: business logic
- Repository: persistence logic
- Job: async workflows and retries
- External Service:
OpenAIClientServiceencapsulates HTTP calls
POST /api/v1/usersvalidates input, delegates toUserService, returnsUserResource.POST /api/v1/ordersvalidates input,OrderServicecreates order and dispatchesAnalyzeUserInterestsjob.- Job loads user, calls
UserInterestAnalysisService. UserInterestAnalysisServicecrafts strict JSON prompt and callsOpenAIClientService.- Parsed JSON is upserted into
user_interests.
- Separation of concerns via controller/service/repository keeps controllers slim and logic testable.
- Async analysis improves latency and availability; failures are retried with exponential backoff.
- Unique job per
user_idprevents thundering herds from rapid order creation. - Strict JSON prompt and parser reduce schema drift and improve durability of stored data.
- Minimal columns loaded during job for efficiency; appropriate indexes to optimize queries.
- Consistency: single-writer per user via
ShouldBeUnique; upsert ensures eventual consistency of interests. - Stability: bounded retries with backoff, structured logging, and explicit error handling.
- Durability: DB transactions handled by Eloquent; idempotent upsert prevents duplication.
- Availability: async background processing decouples API from OpenAI dependency.
- Job:
AnalyzeUserInterestswithtries=5and progressive backoff. - Queue name
analysisallows dedicated workers and tuning.
Add to .env:
OPENAI_API_KEY=sk-...
OPENAI_MODEL=gpt-4o-mini
OPENAI_BASE_URL=https://api.openai.com/v1
OPENAI_TIMEOUT=15
QUEUE_CONNECTION=database
Run migrations and start workers:
php artisan migrate --graceful
php artisan queue:work --queue=analysis --max-time=3600 --tries=5
- Validate controllers with request tests.
- Stub
OpenAIClientServiceto return a consistent JSON payload.