İçeriğe geç
Kodlama ve Yazılım İleri

AI ile Backend Geliştirme: Node.js, Python, Go Best Practices

AI ile backend: Node.js, Python (FastAPI), Go, mikroservis. Database, caching, queue.

YZ
Paylaş:
Sunucu ve veritabanı

Backend = görünmeyen kalbi. AI ile boilerplate kaybolur, focus business logic.

Stack Seçimi

StackUse CaseAI
Node.js (Express/Fastify)JS team, real-time⭐⭐⭐⭐⭐
Python (FastAPI/Django)AI/ML, data⭐⭐⭐⭐⭐
Go (Echo/Gin)Performance, microservice⭐⭐⭐⭐
Rust (Axum)Highest perf, system⭐⭐⭐⭐
Java (Spring Boot)Enterprise⭐⭐⭐⭐
C# (ASP.NET)Microsoft ekosistem⭐⭐⭐⭐
Ruby (Rails)Rapid prototype⭐⭐⭐
Elixir (Phoenix)Concurrent, niche⭐⭐⭐

Project Scaffold

"Aşağıdaki proje için backend scaffold:

Proje: SaaS B2B blog platform API
Stack: Node.js + TypeScript + Fastify
Database: PostgreSQL + Prisma
Cache: Redis
Queue: BullMQ
Search: Meilisearch
Monitoring: OpenTelemetry

Çıktı:
- Folder structure (modular)
- Initial config (env, secrets)
- DB schema
- Auth middleware
- Logging (Pino)
- Error handler
- Health check
- Test setup
- Docker compose (local dev)
- CI/CD outline
"

Architecture Patterns

Layered (Classical)

Controller → Service → Repository → DB

Hexagonal (Ports & Adapters)

Domain ← Application ← Adapters (HTTP, DB, Queue)

Clean Architecture

Entities ← Use Cases ← Interface Adapters ← Frameworks

Event-Driven

Service A → Kafka → Service B
        → Outbox table for reliability
"Aşağıdaki domain için hexagonal:

Domain: Order management

Çıktı:
- Domain entities (Order, OrderItem)
- Domain services (pricing, validation)
- Application use cases (PlaceOrder, CancelOrder)
- Ports (interfaces: OrderRepo, PaymentGateway, EmailService)
- Adapters (PostgresOrderRepo, StripeAdapter, SendGridAdapter)
- HTTP controller
- Unit test (use case)
- Integration test (adapter)
"

Database Operations

Detay: Database Tasarım

Prisma Example

// schema.prisma
model User {
  id        String   @id @default(cuid())
  email     String   @unique
  posts     Post[]
  createdAt DateTime @default(now())
}

model Post {
  id        String   @id @default(cuid())
  title     String
  authorId  String
  author    User     @relation(fields: [authorId], references: [id])
  published Boolean  @default(false)
  
  @@index([authorId])
  @@index([published, createdAt])
}
"Aşağıdaki Prisma query'ler için optimize:

[queries]

Check:
- N+1
- Eager loading (include)
- Lazy field (sensitive data)
- Pagination cursor
- Transaction
- Connection pool
- Read replica
"

Caching Stratejileri

"Cache layer design:

Stack: Redis

Use case 1: User profile
- Cache: SETEX user:{id} 3600
- Invalidate: PROFILE_UPDATE event

Use case 2: Product catalog
- Cache: 1 hour
- Invalidate: cron (every hour)
- Edge: CDN cache headers

Use case 3: Session
- TTL: 7 days
- Sliding window

Cache aside vs write-through vs read-through:
- Cache aside (most): manual fetch + set
- Write-through: write goes through cache
- Read-through: cache fetches on miss

Cache stampede prevention:
- Lock (Redis SET NX)
- Probabilistic early expiration
- Stale-while-revalidate
"

Queue (Background Jobs)

"BullMQ setup:

Queues:
- email-send (priority: high, retry: 3)
- image-resize (priority: low, retry: 5)
- weekly-digest (delayed, schedule)
- export-report (long-running, separate worker)

Producer:
await queue.add('send-email', { userId, template });

Worker:
const worker = new Worker('email', async job => {
  // process
}, { concurrency: 10 });

Monitoring:
- BullMQ UI (Bull Board)
- Failed job alert
- Stuck job detection
- Metrics (rate, latency, error rate)

Dead Letter Queue:
- After max retries
- Manual investigation
- Replay endpoint
"

Real-Time

"WebSocket real-time:

Stack: Socket.IO

Use case:
- Chat (rooms per chat)
- Live notifications
- Collaborative edit
- Live order tracking

Architecture:
- Socket.IO + Redis adapter (scale)
- Sticky session OR Redis pub/sub
- Auth (JWT in handshake)
- Rate limit per connection
- Heartbeat / reconnect
- Room subscription

Server example:
io.on('connection', (socket) => {
  socket.join(`user:${userId}`);
  socket.on('message', handler);
  socket.on('disconnect', cleanup);
});

Alternative:
- Server-Sent Events (one-way push)
- WebTransport (HTTP/3)
- Pusher / Ably (managed)
"

Authentication

"Auth implementation:

Stack: Node.js + Fastify + JWT + bcrypt

Endpoints:
- POST /auth/register
- POST /auth/login
- POST /auth/refresh
- POST /auth/logout
- POST /auth/forgot-password
- POST /auth/reset-password
- POST /auth/verify-email

Security:
- Bcrypt cost 12
- Rate limit (5/min login)
- Account lockout (5 fail)
- Refresh token rotation
- CSRF token (cookie auth)
- httpOnly secure cookies
- JWT short expiry (15 min)
- Refresh token (30 day, DB stored)
- Logout all devices

OAuth:
- Google, Apple, GitHub
- Passport.js strategies
"

Detay: API Tasarım

Error Handling

class AppError extends Error {
  constructor(
    public code: string,
    public statusCode: number,
    message: string,
    public details?: any
  ) {
    super(message);
  }
}

class ValidationError extends AppError {
  constructor(details: any) {
    super('VALIDATION_ERROR', 400, 'Validation failed', details);
  }
}

class NotFoundError extends AppError {
  constructor(resource: string) {
    super('NOT_FOUND', 404, `${resource} not found`);
  }
}

// Global error handler
app.setErrorHandler((error, request, reply) => {
  if (error instanceof AppError) {
    return reply.status(error.statusCode).send({
      error: {
        code: error.code,
        message: error.message,
        details: error.details,
        requestId: request.id
      }
    });
  }
  
  // Unknown error
  logger.error({ err: error, requestId: request.id });
  return reply.status(500).send({
    error: { code: 'INTERNAL_ERROR', message: 'Something went wrong' }
  });
});

Observability

"OpenTelemetry setup:

Auto-instrument:
- HTTP requests
- DB queries
- External API calls
- Cache hits

Manual span:
- Business operation (place order)
- Critical user flow

Metrics (Prometheus):
- request_total{method, route, status}
- request_duration_seconds (histogram)
- active_connections (gauge)
- queue_lag

Traces (Tempo / Jaeger):
- Distributed trace
- Latency breakdown
- Error correlation

Logs (Loki):
- Structured (JSON)
- Trace ID correlation
- Sample DEBUG (1%)
- INFO + WARN + ERROR (full)
"

Detay: DevOps + AI

Testing

Detay: Test Yazma

"Backend test pyramid:

Unit (70%):
- Pure functions
- Mock dependency
- Vitest

Integration (25%):
- DB (test DB)
- Cache (testcontainers)
- HTTP layer
- Use real services

E2E (5%):
- Happy path
- Critical user flow

Test data:
- Factories (Fishery)
- Seed (Prisma seed)
- Cleanup transaction rollback
"

Deployment

"Production deployment:

Container:
- Multi-stage Docker
- Non-root user
- Distroless base
- Health check

K8s:
- Deployment (3+ replicas)
- Service (ClusterIP)
- HPA (CPU + memory)
- PDB
- Network policy

Database:
- Managed (RDS, Cloud SQL)
- Read replica
- Backup automated
- Point-in-time recovery

Secret:
- AWS Secrets Manager
- Vault
- Sealed Secrets

CI/CD:
- GitHub Actions
- Test → build → deploy
- Canary (10% → 100%)
- Automatic rollback (error spike)
"

Yaygın Hatalar

  1. Premature microservice: Monolith düşman değil
  2. No connection pooling: DB exhaust
  3. N+1 ignore: Slow query
  4. Sync everything: Background job for slow
  5. No rate limit: DDoS vulnerable
  6. No monitoring: Production blind
  7. Hardcoded secret: Git history leak
  8. No graceful shutdown: Drop in-flight request

Sonraki Adımlar

Özet

Backend + AI = boilerplate hızlı, focus architecture. Node / Python / Go = top tier. Layered → Hexagonal → Event-driven mature path. Anahtar: monitoring early, security from day 1, sync vs async ayrım.

Paylaş:

Yapay zeka dünyasından haberdar olun

Haftalık özet bültenimize abone olun, en yeni rehberler ve araç incelemeleri direkt e-postanıza gelsin.

İstediğiniz zaman abonelikten çıkabilirsiniz.