Hosting

Marketplace Hosting ve Altyapı

E-ticaret sunucu seçimi, AWS vs Google Cloud vs Azure. CDN, load balancing, auto-scaling, database optimization ve maliyet analizi.

☁️Cloud Provider Karşılaştırması

Marketplace hosting, yüksek trafik, %99.9 uptime ve hızlı yanıt süresi gerektirir. Cloud çözümler orta-büyük ölçek için en uygunudur.

ÖzellikAWSGoogle CloudAzure
Pazar Payı%32 (1. sıra)%10 (3. sıra)%23 (2. sıra)
FiyatlandırmaOrta-YüksekEn UcuzOrta
Hız/PerformansMükemmelÇok İyiÇok İyi
EkosistemEn GenişAI/ML GüçlüMicrosoft Entegrasyon
Best ForBüyük ölçekStartup, AI projelerEnterprise

Marketplace Altyapı Mimarisi (AWS)

# AWS Marketplace Altyapısı (Terraform)
# 1. VPC (Virtual Private Cloud)
resource "aws_vpc" "marketplace_vpc" {
  cidr_block           = "10.0.0.0/16"
  enable_dns_hostnames = true
  enable_dns_support   = true

  tags = {
    Name = "marketplace-vpc"
  }
}

# 2. Load Balancer (ALB - Application Load Balancer)
resource "aws_lb" "marketplace_alb" {
  name               = "marketplace-alb"
  internal           = false
  load_balancer_type = "application"
  security_groups    = [aws_security_group.alb_sg.id]
  subnets            = aws_subnet.public[*].id

  enable_deletion_protection = true
  enable_http2              = true
}

# 3. Auto Scaling Group (Otomatik ölçeklendirme)
resource "aws_autoscaling_group" "marketplace_asg" {
  name                = "marketplace-asg"
  vpc_zone_identifier = aws_subnet.private[*].id
  target_group_arns   = [aws_lb_target_group.marketplace_tg.arn]
  health_check_type   = "ELB"
  health_check_grace_period = 300

  min_size         = 2   # Min 2 instance
  max_size         = 20  # Max 20 instance
  desired_capacity = 4   # Normal: 4 instance

  launch_template {
    id      = aws_launch_template.marketplace_lt.id
    version = "$Latest"
  }

  # CPU %70 üstü → scale out
  # CPU %30 altı → scale in
  tag {
    key                 = "Name"
    value               = "marketplace-instance"
    propagate_at_launch = true
  }
}

# 4. RDS (PostgreSQL) - Multi-AZ
resource "aws_db_instance" "marketplace_db" {
  identifier        = "marketplace-db"
  engine            = "postgres"
  engine_version    = "15.4"
  instance_class    = "db.r6g.xlarge"  # 4 vCPU, 32GB RAM
  allocated_storage = 500  # GB
  storage_type      = "gp3"
  iops             = 12000

  multi_az               = true  # High Availability
  backup_retention_period = 7
  skip_final_snapshot    = false

  db_subnet_group_name   = aws_db_subnet_group.marketplace.name
  vpc_security_group_ids = [aws_security_group.rds_sg.id]

  username = "marketplace_admin"
  password = var.db_password
}

# 5. ElastiCache (Redis) - Caching
resource "aws_elasticache_cluster" "marketplace_redis" {
  cluster_id           = "marketplace-redis"
  engine               = "redis"
  node_type            = "cache.r6g.large"  # 2 vCPU, 13GB RAM
  num_cache_nodes      = 1
  parameter_group_name = "default.redis7"
  engine_version       = "7.0"
  port                 = 6379

  subnet_group_name    = aws_elasticache_subnet_group.marketplace.name
  security_group_ids   = [aws_security_group.redis_sg.id]
}

# 6. S3 (Object Storage) - Images, static files
resource "aws_s3_bucket" "marketplace_assets" {
  bucket = "marketplace-assets"

  versioning {
    enabled = true
  }

  lifecycle_rule {
    id      = "expire-old-versions"
    enabled = true

    noncurrent_version_expiration {
      days = 90
    }
  }
}

# 7. CloudFront (CDN)
resource "aws_cloudfront_distribution" "marketplace_cdn" {
  origin {
    domain_name = aws_s3_bucket.marketplace_assets.bucket_regional_domain_name
    origin_id   = "S3-marketplace-assets"
  }

  enabled             = true
  is_ipv6_enabled     = true
  default_root_object = "index.html"

  default_cache_behavior {
    allowed_methods  = ["GET", "HEAD", "OPTIONS"]
    cached_methods   = ["GET", "HEAD"]
    target_origin_id = "S3-marketplace-assets"

    forwarded_values {
      query_string = false
      cookies {
        forward = "none"
      }
    }

    viewer_protocol_policy = "redirect-to-https"
    min_ttl                = 0
    default_ttl            = 3600    # 1 hour
    max_ttl                = 86400   # 24 hours
  }

  price_class = "PriceClass_100"  # US, Europe

  restrictions {
    geo_restriction {
      restriction_type = "none"
    }
  }

  viewer_certificate {
    acm_certificate_arn = aws_acm_certificate.marketplace_cert.arn
    ssl_support_method  = "sni-only"
  }
}

# 8. Route 53 (DNS)
resource "aws_route53_record" "marketplace_a" {
  zone_id = aws_route53_zone.marketplace.zone_id
  name    = "www.marketplace.com"
  type    = "A"

  alias {
    name                   = aws_cloudfront_distribution.marketplace_cdn.domain_name
    zone_id                = aws_cloudfront_distribution.marketplace_cdn.hosted_zone_id
    evaluate_target_health = false
  }
}

Database Optimization

# PostgreSQL Optimization
# 1. İndeksleme (Indexing)
-- Slow query example
EXPLAIN ANALYZE
SELECT * FROM products WHERE category_id = 5 AND price < 1000;
-- Seq Scan: 5000ms (BAD)

-- Index oluştur
CREATE INDEX idx_products_category_price ON products(category_id, price);

-- Sonrası
EXPLAIN ANALYZE
SELECT * FROM products WHERE category_id = 5 AND price < 1000;
-- Index Scan: 15ms (GOOD - 333x hızlanma!)

# 2. Materialized Views (Önbelleklenmiş sorgular)
CREATE MATERIALIZED VIEW product_stats AS
SELECT
    category_id,
    COUNT(*) as product_count,
    AVG(price) as avg_price,
    SUM(stock) as total_stock
FROM products
GROUP BY category_id;

-- Periyodik refresh (her gece 2'de)
REFRESH MATERIALIZED VIEW CONCURRENTLY product_stats;

-- Kullanım (çok hızlı!)
SELECT * FROM product_stats WHERE category_id = 5;

# 3. Connection Pooling (PgBouncer)
# max_connections = 100 (PostgreSQL)
# PgBouncer → 10,000 concurrent connections → 100 DB connections

# 4. Read Replicas (Okuma yükünü dağıt)
# Master: Write operations
# Replica 1-3: Read operations

-- Python (SQLAlchemy) routing
from sqlalchemy import create_engine

# Master (write)
engine_master = create_engine('postgresql://master-db:5432/marketplace')

# Replica (read)
engine_replica = create_engine('postgresql://replica-db:5432/marketplace')

# Write
with engine_master.connect() as conn:
    conn.execute("INSERT INTO products (...) VALUES (...)")

# Read
with engine_replica.connect() as conn:
    products = conn.execute("SELECT * FROM products WHERE ...")

# 5. Partitioning (Büyük tablolar için)
-- orders tablosu çok büyük (10M+ satır) → yavaş
-- Aylık partition'lara böl

CREATE TABLE orders_2026_02 PARTITION OF orders
FOR VALUES FROM ('2026-02-01') TO ('2026-03-01');

CREATE TABLE orders_2026_03 PARTITION OF orders
FOR VALUES FROM ('2026-03-01') TO ('2026-04-01');

-- Query sadece ilgili partition'da çalışır (hızlı!)
SELECT * FROM orders WHERE created_at BETWEEN '2026-02-15' AND '2026-02-20';

CDN ve Caching Stratejisi

# Multi-layer caching
# 1. Browser Cache (Static assets)
# HTML: Cache-Control: max-age=3600 (1 hour)
# CSS/JS: Cache-Control: max-age=31536000, immutable (1 year)
# Images: Cache-Control: max-age=2592000 (30 days)

# Next.js static optimization
export async function getStaticProps() {
    return {
        props: { products },
        revalidate: 3600  // ISR: 1 saatte bir re-generate
    };
}

# 2. CDN Cache (CloudFront, Cloudflare)
# Edge locations: İstanbul, Frankfurt, Amsterdam
# Hit rate: %80-90 (origin'e gitmeden serve edilir)

# 3. Application Cache (Redis)
import redis
import json

redis_client = redis.Redis(host='redis-endpoint', port=6379)

def get_product(product_id):
    # 1. Redis'te var mı?
    cached = redis_client.get(f"product:{product_id}")
    if cached:
        return json.loads(cached)

    # 2. Yoksa DB'den çek
    product = db.query("SELECT * FROM products WHERE id = %s", product_id)

    # 3. Redis'e kaydet (TTL: 1 hour)
    redis_client.setex(
        f"product:{product_id}",
        3600,
        json.dumps(product)
    )

    return product

# Cache invalidation (ürün güncellendiğinde)
def update_product(product_id, new_data):
    # 1. DB'yi güncelle
    db.execute("UPDATE products SET ... WHERE id = %s", product_id)

    # 2. Cache'i sil (lazy invalidation)
    redis_client.delete(f"product:{product_id}")

    # 3. CDN cache'i invalidate et
    cloudfront_invalidate([f"/products/{product_id}"])

# 4. Database Query Cache
# PostgreSQL: pg_stat_statements extension
# Slow query detection + automatic indexing suggestions

Monitoring ve Alerting

İzlenmesi Gereken Metrikler:

Response Time: p50, p95, p99 latency (hedef: <200ms)
Error Rate: 5xx errors (hedef: <0.1%)
Throughput: Request/second (RPS)
CPU/Memory: Instance utilization (hedef: %60-80)
Database: Connection pool, slow queries, deadlocks
Cache Hit Rate: Redis/CDN (hedef: >80%)
Uptime: Availability (hedef: %99.9)
# CloudWatch Alarms (AWS)
resource "aws_cloudwatch_metric_alarm" "high_cpu" {
  alarm_name          = "marketplace-high-cpu"
  comparison_operator = "GreaterThanThreshold"
  evaluation_periods  = "2"
  metric_name         = "CPUUtilization"
  namespace           = "AWS/EC2"
  period              = "120"
  statistic           = "Average"
  threshold           = "80"
  alarm_description   = "CPU usage above 80%"
  alarm_actions       = [aws_sns_topic.alerts.arn]  # Email/SMS/Slack
}

# Application Performance Monitoring (APM)
# New Relic, Datadog, AWS X-Ray

# Python APM example (New Relic)
import newrelic.agent
newrelic.agent.initialize('newrelic.ini')

@newrelic.agent.background_task()
def process_order(order_id):
    # Otomatik trace edilir
    # - Function execution time
    # - Database queries
    # - External API calls
    pass

Maliyet Optimizasyonu

ÖlçekTrafficÖnerilen AltyapıAylık Maliyet
Başlangıç<10K ziyaret/ayShared hosting (Hostinger, SiteGround)300-800 TL
Küçük10K-100K/ayVPS (DigitalOcean, Linode)1.5K-4K TL
Orta100K-1M/ayAWS EC2 (t3.medium x2) + RDS + Redis15K-30K TL
Büyük1M-10M/ayAuto-scaling (4-12 inst.) + Multi-AZ RDS + CDN60K-150K TL
Enterprise>10M/ayMulti-region, Kubernetes, microservices300K-1M+ TL

Maliyet Tasarrufu İpuçları:

Reserved Instances: 1-3 yıllık taahhüt → %30-60 indirim
Spot Instances: Dev/test ortamları için → %70-90 indirim
Auto-scaling: Gece trafiği düşük → instance sayısını azalt
S3 Lifecycle: Eski veriler → Glacier (archive) → %90 ucuz
CloudFront: Bandwidth maliyetini %50 azaltır
Database: Read replicas yerine caching → daha ucuz

Marketplace Hosting Altyapınızı Kuralım

AWS, Google Cloud veya Azure ile ölçeklenebilir, güvenli ve performanslı e-ticaret altyapısı. CDN, load balancing ve auto-scaling.

Altyapı Danışmanlığı