Skills MCP Model 博客 提交 Skills

DeepSeek Enterprise Solutions

From deployment to operations, covering high-availability architecture, security compliance, permission management, log auditing, monitoring and alerting, and disaster recovery. Includes complete architecture diagrams and configurations to help enterprise-grade AI implementation.

View Solutions

Enterprise Architecture Overview

A complete enterprise-grade DeepSeek inference service architecture, including six core components: API Gateway, load balancing, model service, caching, monitoring, and logging.

1.1 Architecture Panorama

Enterprise-grade DeepSeek deployment adopts a layered architecture, where each layer is independently scalable and replaceable. The core components are as follows:

Layer Component Technology Choice Responsibility
Access Layer API Gateway Kong / APISIX / Nginx Authentication, rate limiting, routing, protocol conversion
Load Balancing Layer Load Balancer Nginx / HAProxy / Envoy Traffic distribution, health checks, session persistence
Inference Layer Model Service vLLM / SGLang / Ollama Model inference, KV Cache management, batching
Cache Layer Cache Redis / Memcached Semantic caching, session caching, rate limiting
Monitoring Layer Monitoring Prometheus + Grafana Metric collection, visualization, alerting
Logging Layer Logging ELK / Loki / ClickHouse Log collection, retrieval, audit, compliance

1.2 Request Flow Path

The complete flow path of an API request:

Client → DNS resolution → CDN/WAF → API Gateway (authentication/rate limiting)
→ Load Balancer (health check/routing) → Model Service (inference)
→ Cache (if semantic cache hit, return directly) → Return result
→ Simultaneously write to Logging (logs) + Monitoring (metrics)

1.3 Architecture Design Principles

  • High Availability: Each component has at least two replicas, with automatic failover.
  • Scalability: Horizontally scale inference nodes, elastic scaling.
  • Observability: Full-chain tracing, metric visualization, automated alerting.
  • Security and Compliance: Encryption in transit, access control, audit logs.
  • Cost Control: Token metering, department cost allocation, budget alerts.

High Availability Deployment

Multi-node deployment, auto-scaling, health checks, failover strategies. Ensure 99.9% availability for DeepSeek inference services.

2.1 Multi-node Deployment Architecture

Deploy at least 3 inference nodes across different physical machines or availability zones to avoid single points of failure:

# Multi-node vLLM deployment (3-node cluster)
# Node 1 (192.168.1.11)
python -m vllm.entrypoints.openai.api_server \
--model deepseek-ai/DeepSeek-R1-Distill-Qwen-32B \
--tensor-parallel-size 2 \
--host 0.0.0.0 --port 8000

# Node 2 (192.168.1.12)
python -m vllm.entrypoints.openai.api_server \
--model deepseek-ai/DeepSeek-R1-Distill-Qwen-32B \
--tensor-parallel-size 2 \
--host 0.0.0.0 --port 8000

# Node 3 (192.168.1.13)
python -m vllm.entrypoints.openai.api_server \
--model deepseek-ai/DeepSeek-R1-Distill-Qwen-32B \
--tensor-parallel-size 2 \
--host 0.0.0.0 --port 8000

2.2 Health Check Configuration

The load balancer needs to periodically probe the health status of backend services and automatically remove faulty nodes:

# Nginx health check configuration
upstream deepseek_cluster {
server 192.168.1.11:8000 max_fails=3 fail_timeout=30s;
server 192.168.1.12:8000 max_fails=3 fail_timeout=30s;
server 192.168.1.13:8000 max_fails=3 fail_timeout=30s;

# Active health check (requires nginx-plus or nginx-module)
# check interval=3000 rise=2 fall=3 timeout=1000 type=http;
# check_http_send "HEAD /health HTTP/1.0\r\n\r\n";
# check_http_expect_alive http_2xx;
}

# Custom health check script
# /usr/local/bin/healthcheck-vllm.sh
#!/bin/bash
for node in 192.168.1.11 192.168.1.12 192.168.1.13; do
status=$(curl -s -o /dev/null -w "%{http_code}" http://$node:8000/health)
if [ "$status" != "200" ]; then
echo "ALERT: Node $node is DOWN" | systemd-cat -t healthcheck
# Trigger alert notification
fi
done

2.3 Failover Strategy

Failure Type Detection Method Recovery Strategy RTO
Node Down Health check fails 3 times Automatically remove, traffic switches to other nodes < 30s
GPU OOM vLLM process exits systemd auto-restart, K8s auto-recreate Pod < 60s
Network Partition Heartbeat timeout between nodes Remove isolated nodes, recover after arbitration < 10s
Entire availability zone failure Multiple nodes unreachable simultaneously DNS switch to backup availability zone < 5min

2.4 Kubernetes HA Configuration

# deepseek-ha-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: deepseek-vllm
namespace: deepseek
spec:
replicas: 3
selector:
matchLabels:
app: deepseek-vllm
template:
metadata:
labels:
app: deepseek-vllm
spec:
# Pod anti-affinity: ensure Pods are spread across different nodes
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: app
operator: In
values:
- deepseek-vllm
topologyKey: kubernetes.io/hostname
# Graceful termination: give Pod 30 seconds to finish current requests
terminationGracePeriodSeconds: 30
containers:
- name: vllm
image: vllm/vllm-openai:latest
ports:
- containerPort: 8000
resources:
requests:
nvidia.com/gpu: 2
memory: "64Gi"
limits:
nvidia.com/gpu: 2
memory: "80Gi"
livenessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 120
periodSeconds: 10
failureThreshold: 3
readinessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 60
periodSeconds: 5
failureThreshold: 3
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1
maxSurge: 1

2.5 Auto-scaling (HPA)

# deepseek-hpa.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: deepseek-vllm-hpa
namespace: deepseek
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: deepseek-vllm
minReplicas: 3
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
behavior:
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 50
periodSeconds: 60
scaleUp:
stabilizationWindowSeconds: 30
policies:
- type: Pods
value: 2
periodSeconds: 30

Load Balancing

Nginx upstream configuration, least_conn algorithm, Sticky Session, connection pool, Keepalive optimization. Ensure even traffic distribution and maximize GPU utilization.

3.1 Nginx Upstream Configuration

# /etc/nginx/conf.d/deepseek-upstream.conf
upstream deepseek_vllm {
# least_conn algorithm: prioritize nodes with fewest connections
# Suitable for LLM inference scenarios (large variance in request latency)
least_conn;

# Inference node pool
server 192.168.1.11:8000 weight=1 max_fails=3 fail_timeout=30s;
server 192.168.1.12:8000 weight=1 max_fails=3 fail_timeout=30s;
server 192.168.1.13:8000 weight=1 max_fails=3 fail_timeout=30s;

# Backup node (low priority, only enabled when all primary nodes fail)
server 192.168.1.14:8000 weight=1 backup;

# Long connection pool: reduce TCP handshake overhead
keepalive 64;
keepalive_requests 1000;
keepalive_timeout 60s;
}

# vLLM inference service (high performance)
upstream deepseek_vllm_large {
least_conn;
server 192.168.1.21:8000 weight=3; # A100 × 8 (high weight)
server 192.168.1.22:8000 weight=3; # A100 × 8
server 192.168.1.23:8000 weight=1; # A10 × 1 (low weight)
keepalive 32;
}

3.2 Sticky Session (Session Persistence)

In LLM inference scenarios, Sticky Session can route consecutive requests from the same user to the same node, improving KV Cache hit rate:

# Cookie-based session persistence
upstream deepseek_sticky {
# ip_hash algorithm: same client IP always routes to the same node
ip_hash;

server 192.168.1.11:8000;
server 192.168.1.12:8000;
server 192.168.1.13:8000;
}

# Using sticky cookie (requires nginx-plus or sticky-module)
upstream deepseek_sticky_cookie {
# sticky cookie srv_id expires=1h domain=.example.com path=/;
server 192.168.1.11:8000;
server 192.168.1.12:8000;
server 192.168.1.13:8000;
}

3.3 Connection Pool and Keepalive Optimization

Parameter Recommended Value Description
keepalive 32-64 Number of idle connections kept, reducing handshake overhead
keepalive_requests 1000 Maximum requests per connection, preventing connection leaks
keepalive_timeout 60s Idle connection timeout
proxy_http_version 1.1 HTTP/1.1 supports Keep-Alive
proxy_set_header Connection "" Clear Connection header to enable connection reuse

3.4 Load Balancing Algorithm Comparison

Algorithm Principle Applicable Scenario Recommendation
round-robin Round-robin distribution Nodes with identical configuration Three stars
least_conn Assign to node with fewest connections Large variance in request latency (recommended for LLM) Five stars
ip_hash Hash based on client IP Session persistence needed, KV Cache reuse Four stars
least_time Assign to node with fastest response Heterogeneous node performance Four stars (requires nginx-plus)

Security Hardening

API authentication (JWT/OAuth2), rate limiting, IP whitelist, request validation, prompt injection protection, data encryption. Build a multi-layered security defense system.

4.1 API Authentication Schemes

Supports two authentication methods: JWT (JSON Web Token) and OAuth2, adapting to different scenarios:

JWT Authentication (Service-to-Service Calls)

# JWT Token Generation (Server-side)
# Python Example
import jwt
import time

def generate_api_token(user_id: str, scope: str = "deepseek:read") -> str:
payload = {
"sub": user_id,
"scope": scope,
"iat": int(time.time()),
"exp": int(time.time()) + 3600 # 1 hour expiration
}
return jwt.encode(payload, "your-secret-key", algorithm="HS256")

# Nginx JWT Validation (using njs or lua-nginx-module)
# Add JWT validation logic in location block
location /v1/ {
auth_jwt "DeepSeek API";
auth_jwt_key_file /etc/nginx/jwt_public_key.pem;
proxy_pass http://deepseek_vllm;
}

OAuth2 Authentication (User Authorization)

# Kong API Gateway OAuth2 Plugin Configuration
# Enable OAuth2 plugin
curl -X POST http://localhost:8001/services/deepseek/plugins \
--data "name=oauth2" \
--data "config.enable_authorization_code=true" \
--data "config.enable_client_credentials=true" \
--data "config.token_expiration=3600"

# Create OAuth2 application
curl -X POST http://localhost:8001/consumers/your-app/oauth2 \
--data "name=DeepSeek App" \
--data "client_id=your-client-id" \
--data "client_secret=your-client-secret" \
--data "redirect_uris[]=https://your-app.com/callback"

4.2 Rate Limiting

# Nginx Rate Limiting Configuration
# /etc/nginx/nginx.conf
http {
# Rate limit by IP: 10 requests/second, burst 20
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;

# Rate limit by API Key: 50 requests/second
limit_req_zone $http_x_api_key zone=per_key_limit:10m rate=50r/s;

# Concurrent connection limit
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
}

# Apply in Server block
server {
location /v1/chat/completions {
# Basic rate limiting
limit_req zone=api_limit burst=20 nodelay;
limit_req_status 429;

# Rate limit by API Key
limit_req zone=per_key_limit burst=50 nodelay;

# Concurrent limit
limit_conn conn_limit 10;

proxy_pass http://deepseek_vllm;
}
}

4.3 IP Whitelist

# Nginx IP Whitelist
location /v1/admin/ {
# Allow only internal and VPN network segments
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
deny all;

proxy_pass http://deepseek_vllm;
}

# Use GeoIP module to restrict country/region
# geoip_country /usr/share/GeoIP/GeoIP.dat;
# map $geoip_country_code $allowed_country {
# default no;
# CN yes;
# US yes;
# }

4.4 Request Validation

Validate requests at the API Gateway layer to prevent malicious or abnormal requests:

# Nginx Request Validation
location /v1/chat/completions {
# Limit request body size
client_max_body_size 1M;

# Allow only POST method
limit_except POST {
deny all;
}

# Restrict Content-Type
if ($http_content_type !~ "^application/json") {
return 415 '{"error":"Unsupported Media Type"}'; }
# Limit max_tokens parameter (prevent resource abuse)
# Requires lua-nginx-module or njs

proxy_pass http://deepseek_vllm;
}

4.5 Prompt Injection Protection

Prompt injection is one of the major security threats facing enterprise AI applications. Attackers bypass system instructions through carefully crafted prompts to obtain sensitive information or perform unauthorized operations.

Protection measures:

  • Input filtering: Detect and filter known injection patterns (e.g., keywords like "ignore previous instructions", "system prompt")
  • Output review: Detect sensitive information in model output (PII, keys, internal IPs)
  • Role separation: Strictly separate system prompts from user input, use special delimiters
  • Least privilege: Model can only access data and tools within its authorized scope
  • Content safety API: Integrate third-party content safety services to detect violating content in real time

# Python example for prompt injection detection
import re

INJECTION_PATTERNS = [
r"ignore\s+(all\s+)?(previous|above|prior)\s+instructions?",
r"you\s+are\s+now\s+(DAN|jailbreak)",
r"system\s*prompt[:=]",
r"pretend\s+you\s+are",
r"<\|im_start\|>",
r"<\|im_end\|>",
]

def detect_injection(user_input: str) -> bool:
for pattern in INJECTION_PATTERNS:
if re.search(pattern, user_input, re.IGNORECASE):
return True
return False

4.6 Data Encryption

Encryption Layer Solution Description
Transport Encryption TLS 1.3 Enforce HTTPS for all API communications
Storage Encryption AES-256-GCM Encrypt sensitive data in logs, caches, and backups
Key Management HashiCorp Vault / AWS KMS Centralized key management, automatic rotation, access auditing
Database Encryption TDE + Column-level encryption Encrypted storage for PII data (API keys, user information)

Permission Management

RBAC model, multi-tenant isolation, API key management, usage quotas, department-level access control. Achieve fine-grained permission control.

5.1 RBAC Permission Model

Role-Based Access Control (RBAC) defines the mapping between roles, permissions, and resources:

Role Permission Scope Typical Users
Super Admin All permissions: system configuration, user management, model management Platform operations team
Dept Admin User management within department, usage viewing, quota allocation Department head
Developer API calls, model selection, view own usage Development engineers
Viewer View usage reports and model list only Non-technical personnel
Auditor View audit logs, compliance reports Compliance/Security team

5.2 Multi-Tenant Isolation

Multi-tenant isolation is a hard requirement for enterprise-grade platforms. Recommended solutions:

  • Logical isolation: Same inference cluster, tenants distinguished by API keys, suitable for small to medium scale
  • Namespace isolation: K8s Namespace-level isolation, each tenant has independent Deployment
  • Cluster isolation: Independent GPU clusters, physical isolation, suitable for highly compliant scenarios like finance and healthcare
  • Model isolation: Different tenants use different model instances, fully isolating KV Cache

5.3 API Key Management

# API Key Management Best Practices
# 1. Key Generation
openssl rand -hex 32 # 64-character random Key

# 2. Key Storage (hash storage, no plaintext)
import hashlib
import secrets

def create_api_key() -> tuple[str, str]:
raw_key = "sk-" + secrets.token_hex(24)
hashed = hashlib.sha256(raw_key.encode()).hexdigest()
return raw_key, hashed # plaintext returned to user, hash stored in DB

# 3. Key Verification
def verify_api_key(raw_key: str, stored_hash: str) -> bool:
return hashlib.sha256(raw_key.encode()).hexdigest() == stored_hash

# 4. Key Permission Binding
api_key_config = {
"key_hash": "abc123...",
"tenant_id": "tenant-001",
"role": "developer",
"rate_limit": 100, # requests/minute
"daily_quota": 1000000, # Token/day
"allowed_models": ["deepseek-v3", "deepseek-r1"],
"expires_at": "2026-12-31T23:59:59Z"
}

5.4 Usage Quota Management

Quota Type Granularity Example
Token Quota Per day/month/year 1 million Token/day per user
Request Quota Per minute/hour 60 requests/minute per API Key
Concurrency Quota Real-time Max 10 concurrent requests per tenant
Model Quota Per model V3 unlimited, R1 limited to 100k Token/day

5.5 Department-Level Access Control

# Department-level permission configuration example
departments:
engineering:
quota: 5000000 # 5 million Token/day
models: [deepseek-v3, deepseek-r1, deepseek-coder]
rate_limit: 200
members: [user1, user2, user3]

marketing:
quota: 1000000 # 1 million Token/day
models: [deepseek-v3]
rate_limit: 50
members: [user4, user5]

finance:
quota: 500000
models: [deepseek-v3]
rate_limit: 30
members: [user6]
# Finance department special restriction: disable streaming output
features:
streaming: false

Logging and Audit

Request logging, user activity tracking, compliance auditing, log retention policies, ELK Stack integration. Meets compliance requirements such as MLPS and GDPR.

6.1 Request Logging

Comprehensively record metadata for each API request for auditing, billing, and troubleshooting:

# Nginx audit log format
# /etc/nginx/conf.d/deepseek-log.conf
log_format deepseek_audit escape=json
'{'
'"timestamp":"$time_iso8601",'
'"remote_addr":"$remote_addr",'
'"api_key":"$http_x_api_key",'
'"request_method":"$request_method",'
'"request_uri":"$request_uri",'
'"status":$status,'
'"body_bytes_sent":$body_bytes_sent,'
'"request_time":$request_time,'
'"upstream_addr":"$upstream_addr",'
'"upstream_response_time":"$upstream_response_time",'
'"user_agent":"$http_user_agent",'
'"x_forwarded_for":"$http_x_forwarded_for"'
'}';

access_log /var/log/nginx/deepseek-audit.log deepseek_audit buffer=64k flush=5s;

6.2 User Activity Tracking

Record user operations at the application layer to build a complete audit trail:

# Python audit log middleware
import logging
import json
from datetime import datetime, timezone

audit_logger = logging.getLogger("deepseek.audit")

def log_api_call(user_id: str, action: str, details: dict):
audit_entry = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"user_id": user_id,
"action": action, # "chat.completion", "model.list", etc.
"model": details.get("model"),
"prompt_tokens": details.get("prompt_tokens"),
"completion_tokens": details.get("completion_tokens"),
"total_tokens": details.get("total_tokens"),
"latency_ms": details.get("latency_ms"),
"ip_address": details.get("ip_address"),
"user_agent": details.get("user_agent"),
"status": details.get("status"), # "success" | "error"
}
audit_logger.info(json.dumps(audit_entry, ensure_ascii=False))

6.3 Compliance Audit Requirements

Compliance Standard Logging Requirements Retention Period
MLPS 2.0 (Level 3) User login, operations, configuration changes, abnormal events At least 6 months
GDPR Records of data processing activities, data access logs, consent records As needed (data minimization principle)
SOC 2 Access control, change management, system operations, security incidents At least 12 months
ISO 27001 Information security incidents, access control, operation logs Determined by risk assessment

6.4 Log Retention Policy

# Logrotate configuration
# /etc/logrotate.d/deepseek
/var/log/deepseek/*.log {
daily
rotate 90 # retain for 90 days
compress
delaycompress
missingok
notifempty
dateext
dateformat -%Y%m%d
postrotate
# Send signal to Nginx to reopen log files
/usr/bin/killall -USR1 nginx 2>/dev/null || true
endscript
}

# Audit logs (meeting compliance requirements, retain for 6 months)
/var/log/deepseek/audit/*.log {
daily
rotate 180
compress
delaycompress
missingok
notifempty
dateext
# Archive to object storage (S3/OSS)
lastaction
/usr/local/bin/archive-logs.sh
endscript
}

6.5 ELK Stack Integration

# Filebeat configuration: collect Nginx logs and send to Elasticsearch
# /etc/filebeat/filebeat.yml
filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/nginx/deepseek-audit.log
json.keys_under_root: true
json.add_error_key: true
fields:
service: deepseek-api
log_type: audit
fields_under_root: true

output.elasticsearch:
hosts: ["https://elasticsearch.example.com:9200"]
username: "filebeat_writer"
password: "${ES_PASSWORD}"
index: "deepseek-audit-%{+yyyy.MM.dd}"

# ILM policy: hot data 7 days, warm data 30 days, cold data 90 days
setup.ilm.enabled: true
setup.ilm.rollover_alias: "deepseek-audit"
setup.ilm.pattern: "{now/d}-000001"
setup.ilm.policy_name: "deepseek-audit-policy"

Monitoring and Alerting

Prometheus metrics collection, Grafana visualization dashboards, AlertManager alert rules, SLA monitoring, cost tracking.

7.1 Prometheus Metrics Collection

vLLM has built-in Prometheus metrics endpoint, ready to use out of the box:

# prometheus.yml
global:
scrape_interval: 15s
evaluation_interval: 15s

alerting:
alertmanagers:
- static_configs:
- targets: ['alertmanager:9093']

rule_files:
- '/etc/prometheus/rules/deepseek-alerts.yml'

scrape_configs:
- job_name: 'vllm'
scrape_interval: 10s
static_configs:
- targets:
- 'vllm-node-1:8000'
- 'vllm-node-2:8000'
- 'vllm-node-3:8000'
metrics_path: '/metrics'

- job_name: 'nginx'
static_configs:
- targets: ['nginx-exporter:9113']

- job_name: 'node'
static_configs:
- targets:
- 'node-exporter-1:9100'
- 'node-exporter-2:9100'
- 'node-exporter-3:9100'

- job_name: 'dcgm' # NVIDIA GPU metrics
static_configs:
- targets: ['dcgm-exporter:9400']

7.2 Grafana Dashboards

It is recommended to import the following Grafana Dashboard templates:

Dashboard ID Purpose
NVIDIA DCGM Exporter 19004 GPU utilization, temperature, power consumption, memory
Node Exporter Full 1860 CPU, memory, disk, network
Nginx 11168 Request volume, latency, error rate, connections
vLLM Custom Self-built TTFT, TPOT, TPS, queue length

7.3 AlertManager Alert Rules

# /etc/prometheus/rules/deepseek-alerts.yml
groups:
- name: deepseek_sla
rules:
# Availability alert
- alert: DeepSeekServiceDown
expr: up{job="vllm"} == 0
for: 1m
labels:
severity: critical
team: platform
annotations:
summary: "DeepSeek inference service unavailable"
description: "Node {{ $labels.instance }} has been down for more than 1 minute"

# Latency alert
- alert: HighLatency
expr: histogram_quantile(0.95, rate(vllm:time_to_first_token_seconds_bucket[5m])) > 2
for: 5m
labels:
severity: warning
annotations:
summary: "TTFT P95 exceeds 2 seconds"

# GPU memory alert
- alert: GPUMemoryHigh
expr: vllm:gpu_cache_usage_perc > 90
for: 5m
labels:
severity: warning
annotations:
summary: "GPU memory usage exceeds 90%"

# Queue backlog alert
- alert: RequestQueueBacklog
expr: vllm:num_requests_waiting > 20
for: 3m
labels:
severity: warning
annotations:
summary: "Request queue backlog exceeds 20"

# Error rate alert
- alert: HighErrorRate
expr: rate(vllm:request_errors_total[5m]) / rate(vllm:request_total[5m]) > 0.05
for: 5m
labels:
severity: critical
annotations:
summary: "API error rate exceeds 5%"

# Cost alert
- alert: HighCostDaily
expr: increase(vllm:total_tokens_generated[24h]) * 0.000002 > 100
for: 1h
labels:
severity: info
annotations:
summary: "Estimated daily token cost exceeds $100"

7.4 SLA Monitoring

# Prometheus SLA recording rules
# /etc/prometheus/rules/deepseek-sla.yml
groups:
- name: deepseek_sla_recording
interval: 1m
rules:
# Availability percentage
- record: job:availability:ratio
expr: avg(up{job="vllm"})

# Success request rate
- record: job:success_rate:ratio
expr: |
sum(rate(vllm:request_success_total[5m]))
/
sum(rate(vllm:request_total[5m]))

# P50/P95/P99 latency
- record: job:ttft:p50
expr: histogram_quantile(0.50, rate(vllm:time_to_first_token_seconds_bucket[5m]))

- record: job:ttft:p95
expr: histogram_quantile(0.95, rate(vllm:time_to_first_token_seconds_bucket[5m]))

- record: job:ttft:p99
expr: histogram_quantile(0.99, rate(vllm:time_to_first_token_seconds_bucket[5m]))

Disaster Recovery Plan

Model backup, configuration backup, multi-region deployment, disaster recovery RTO/RPO, failover drills. Ensure business continuity under extreme conditions.

8.1 Model Backup Strategy

Backup Content Backup Method Frequency Storage Location
Model weight files Object storage + local NAS On version update S3/OSS + local storage
Inference configuration Git repository On every change GitHub/GitLab + multi-region
Nginx configuration Git repository + configuration management On every change Git + Ansible/Helm
K8s resource definitions GitOps (ArgoCD/Flux) On every change Git repository
Audit logs Object storage archive Daily S3 Glacier / OSS archive

8.2 Multi-Region Deployment Architecture

# Multi-region DNS configuration (Route 53 / Cloud DNS)
# Primary region: ap-southeast-1 (Singapore)
# Standby region: us-west-2 (Oregon)

# Intelligent DNS routing policy
Record: api.deepseek.example.com
Type: A (Alias)
Routing: Latency-based

# Primary region
ap-southeast-1:
- api.deepseek.example.com → primary cluster LB (103.x.x.x)

# Standby region (hot standby)
us-west-2:
- api.deepseek.example.com → standby cluster LB (54.x.x.x)

# Failover configuration
# Health check: probe primary cluster /health every 30 seconds
# 3 consecutive failures → automatically switch to standby region
# Primary cluster recovery → automatically switch back

8.3 RTO/RPO Definition

Metric Definition Target Value Implementation
RTO Recovery Time Objective (how long to restore service) < 15 minutes DNS failover + K8s auto-rebuild
RPO Recovery Point Objective (how much data loss) < 1 minute Real-time sync + transaction logs

8.4 Failover Drill

# Failover drill script
#!/bin/bash
# failover-drill.sh

echo "=== Failover drill started ==="
echo "Time: $(date)"

# 1. Simulate primary cluster failure
echo "[1/5] Simulating primary cluster failure..."
kubectl scale deployment deepseek-vllm --replicas=0 -n deepseek
sleep 10

# 2. Verify DNS switch
echo "[2/5] Verifying DNS switch..."
PRIMARY_HEALTH=$(curl -s -o /dev/null -w "%{http_code}" https://primary-api.example.com/health)
BACKUP_HEALTH=$(curl -s -o /dev/null -w "%{http_code}" https://backup-api.example.com/health)
echo "Primary cluster: HTTP $PRIMARY_HEALTH"
echo "Backup cluster: HTTP $BACKUP_HEALTH"

# 3. Verify API availability
echo "[3/5] Verifying API availability..."
curl -s https://api.deepseek.example.com/v1/models | jq .

# 4. Verify data consistency
echo "[4/5] Verifying data consistency..."
# Check if audit logs from the last 1 minute are complete

# 5. Restore primary cluster
echo "[5/5] Restoring primary cluster..."
kubectl scale deployment deepseek-vllm --replicas=3 -n deepseek

echo "=== Failover drill completed ==="
echo "RTO: Record actual recovery time"
echo "RPO: Check for data loss"

It is recommended to conduct a full failover drill quarterly to verify that RTO/RPO meet targets and to identify any gaps in the plan. Visit DeepSeek Deployment Tutorial for basic deployment solutions.

Cost Control

Token usage tracking, per-department cost allocation, budget alerts, model tiering strategy, cache optimization. Maximize ROI and control AI inference costs.

9.1 Token Usage Tracking

# Token usage statistics SQL example (ClickHouse)
CREATE TABLE token_usage (
timestamp DateTime,
api_key String,
tenant_id String,
department String,
model String,
prompt_tokens UInt64,
completion_tokens UInt64,
total_tokens UInt64
) ENGINE = MergeTree()
PARTITION BY toYYYYMM(timestamp)
ORDER BY (tenant_id, department, timestamp);

# Daily usage by department
SELECT
department,
toDate(timestamp) as date,
sum(total_tokens) as daily_tokens,
sum(prompt_tokens) as prompt_tokens,
sum(completion_tokens) as completion_tokens
FROM token_usage
WHERE timestamp >= now() - INTERVAL 30 DAY
GROUP BY department, date
ORDER BY department, date;

9.2 Per-Department Cost Allocation

Department Monthly Tokens Estimated Cost Quota Usage Status
R&D 45,000,000 ¥450 90% Near limit
Marketing 12,000,000 ¥120 40% Normal
Customer Service 80,000,000 ¥800 80% Normal
Finance 2,000,000 ¥20 10% Low usage

9.3 Budget Alert Configuration

# Prometheus budget alert rules
groups:
- name: cost_alerts
rules:
# Department budget usage alert
- alert: DeptBudget80Percent
expr: |
(sum by (department) (increase(vllm:total_tokens[30d])) * 0.01)
/
(dept_budget_limit) > 0.8
for: 1h
labels:
severity: warning
annotations:
summary: "Department {{ $labels.department }} budget usage exceeds 80%"

# Daily cost spike alert
- alert: CostSpike
expr: |
(sum(increase(vllm:total_tokens[1h])) * 0.01)
>
(sum(increase(vllm:total_tokens[1h] offset 24h)) * 0.01) * 3
for: 30m
labels:
severity: critical
annotations:
summary: "Token consumption increased by more than 300% compared to the same time yesterday"

9.4 Model Tiering Strategy

Intelligently route to different models based on task complexity to avoid "using a sledgehammer to crack a nut":

Task Type Recommended Model Relative Cost Examples
Simple Q&A DeepSeek V3 1x Translation, summarization, classification
Code Generation DeepSeek Coder 1x Code completion, bug fixing
Complex Reasoning DeepSeek R1 4x Mathematical proof, logical analysis
Cache Hit Return cache directly 0x Repeated questions, common prompts

9.5 Caching Strategy

Semantic caching can significantly reduce inference costs, returning cached results directly for repeated or similar questions:

# Redis semantic cache configuration
# Use GPTCache or LangChain Cache
from gptcache import cache
from gptcache.adapter import openai
from gptcache.embedding import Onnx
from gptcache.manager import CacheBase, VectorBase, get_data_manager
from gptcache.similarity_evaluation.distance import SearchDistanceEvaluation

# Initialize semantic cache
onnx_embedding = Onnx()
data_manager = get_data_manager(
CacheBase("redis", host="redis-cache", port=6379),
VectorBase("milvus", host="milvus", port="19530")
)

cache.init(
embedding_func=onnx_embedding.to_embeddings,
data_manager=data_manager,
similarity_evaluation=SearchDistanceEvaluation(),
similarity_threshold=0.85 # Similarity threshold
)

# Expected cache hit rate
# Customer service scenario: 30%-50%
# Code generation: 10%-20%
# General Q&A: 20%-40%

Semantic caching can save 20%-40% of inference costs. Visit DeepSeek Usage Guide and DeepSeek Model Details to learn about model selection.

Compliance and Data Privacy

Data residency, GDPR compliance, data masking, model cards, responsible AI guidelines. Ensure AI applications comply with global data protection regulations.

10.1 Data Residency

Ensure user data is stored in designated geographic regions to meet data sovereignty requirements of different countries/regions:

User Region Data Storage Region Inference Nodes Regulatory Basis
Mainland China Alibaba Cloud / Huawei Cloud (domestic) Domestic GPU clusters Data Security Law, Personal Information Protection Law
European Union AWS Frankfurt / GCP europe-west EU GPU clusters GDPR
Asia Pacific AWS Singapore Singapore GPU clusters PDPA (Singapore)

10.2 GDPR Compliance Checklist

  • Data Minimization: Collect only necessary data; do not store PII in prompt logs
  • User Consent: Clearly inform data processing methods before first use and obtain explicit consent
  • Data Portability: Provide user data export functionality (JSON/CSV format)
  • Right to Erasure: Support user requests to delete all associated data (within 30 days)
  • Data Processing Agreement (DPA): Sign DPAs with third-party service providers
  • Data Protection Impact Assessment (DPIA): Complete DPIA for AI inference scenarios
  • Data Protection Officer (DPO): Designate a DPO and publish contact information
  • 72-Hour Notification: Report data breaches to supervisory authorities within 72 hours

10.3 Data Masking

Automatically detect and mask sensitive information before sending prompts to the model:

# Python data masking middleware
import re
from presidio_analyzer import AnalyzerEngine
from presidio_anonymizer import AnonymizerEngine

analyzer = AnalyzerEngine()
anonymizer = AnonymizerEngine()

def anonymize_prompt(text: str) -> str:
# Detect PII entities
results = analyzer.analyze(
text=text,
entities=["PHONE_NUMBER", "EMAIL_ADDRESS",
"PERSON", "CREDIT_CARD", "IBAN_CODE",
"CN_ID", "PASSPORT_NUMBER"],
language="zh"
)

# Anonymize
anonymized = anonymizer.anonymize(text=text, analyzer_results=results)
return anonymized.text

# Example
original = "我的手机号是 13812345678,邮箱是 zhang@example.com"
safe = anonymize_prompt(original)
# Output: "我的手机号是 <PHONE_NUMBER>,邮箱是 <EMAIL_ADDRESS>"

10.4 Model Cards

Each model instance should maintain a model card documenting the model's basic information, capability boundaries, and risk warnings:

Model Card Field Description
Model Name DeepSeek-V3 / DeepSeek-R1
Model Version v3.0-2026-01
Training Data Cutoff Date 2025-12-31
Supported Languages Chinese, English, Japanese, Korean, and 20+ languages
Known Limitations No real-time information, may hallucinate, not for medical diagnosis
Bias Evaluation Passed standard bias test sets; see technical report for details
Usage Restrictions Prohibited from generating illegal content, not for automated decision-making in high-impact scenarios

10.5 Responsible AI Guidelines

Core principles for enterprise AI use:

  • Transparency: Clearly identify AI-generated content to users; do not impersonate humans
  • Fairness: Regularly evaluate model output bias to ensure fair treatment of different groups
  • Explainability: Provide reasoning processes for key decision scenarios and support human review
  • Human Oversight: High-risk decisions (medical, legal, financial) must include human review
  • Continuous Monitoring: Establish AI output quality monitoring and regularly evaluate model performance and safety
  • Safety First: Content safety filtering, jailbreak detection, emergency circuit breakers
  • Sustainable development: Focus on the carbon emissions of model inference and optimize the energy efficiency ratio.

Responsible AI is not a one-time effort but a continuous process. It is recommended to establish an AI governance committee to regularly review the risks and compliance of AI applications. Visit the DeepSeek model list and prompt engineering to learn more best practices.

DeepSeek Enterprise Application FAQ

How many GPUs are needed for DeepSeek enterprise deployment? +
It depends on the model size and concurrency. For the 8B model: a single A10 (24GB) can support 20-50 concurrent requests; for the 32B model: 2 A100s can support 50-100 concurrent requests; for the 70B model: 4 A100s can support 50-100 concurrent requests; for the 671B model: at least 8 H100s. It is recommended to start with 3 nodes and scale out based on actual load. If the budget is limited, you can first validate the scenario using the DeepSeek official API, then decide on the scale of self-hosting.
How can enterprises ensure data security and compliance? +
Core measures include: 1) Full-chain encryption at the transport and storage layers (TLS 1.3 + AES-256); 2) API authentication using JWT/OAuth2, with IP whitelisting and rate limiting; 3) Automatic desensitization of prompt inputs (PII detection); 4) Complete audit logs to meet compliance requirements such as MLPS 2.0 and GDPR; 5) Multi-tenant isolation (logical or physical); 6) Data residency policies to ensure data does not leave the country (if required). It is recommended to conduct regular security penetration testing and compliance audits.
How to achieve 99.9% availability? +
Multi-node deployment (at least 3 nodes) + load balancing + health checks + automatic failover. When deploying on K8s, configure Pod anti-affinity to ensure physical dispersion of nodes, and use HPA for auto-scaling. For critical business, multi-AZ deployment (active-standby) is recommended, with DNS intelligent routing for cross-region failover. RTO target is less than 15 minutes, RPO target is less than 1 minute. Conduct failover drills quarterly.
How to control the cost of enterprise deployment? +
1) Model tiering: use V3 for simple tasks (1x cost), and R1 only for complex reasoning (4x cost); 2) Semantic caching: can reduce inference volume by 20%-40%; 3) Departmental quotas and budget alerts to prevent abuse; 4) Use spot/preemptible GPU instances (cost reduction of 60%-80%), suitable for non-real-time tasks; 5) Prioritize the 8B model, which is sufficient for most scenarios; 6) Hybrid approach: self-host for high-concurrency core business, and use the official API for long-tail needs. With reasonable configuration, monthly costs can be controlled within tens of thousands of yuan.
How to prevent prompt injection attacks? +
Multi-layer defense strategy: 1) Input filtering layer: detect known injection patterns (such as "ignore instructions", "system prompt", etc.), using regex matching + semantic detection; 2) Role separation: strictly isolate system prompts from user input with special delimiters; 3) Output review layer: perform sensitive information detection and content security review on model outputs; 4) Least privilege: the model only accesses authorized tools and data to avoid privilege escalation; 5) Circuit breaker mechanism: automatically interrupt the session when abnormal behavior is detected. It is recommended to integrate a professional content security API as a fallback.
What are the advantages of enterprise deployment compared to the official API? +
Advantages of self-hosted deployment: 1) Data is fully private and does not pass through third-party servers, suitable for highly regulated scenarios such as finance and healthcare; 2) Customizable models (fine-tuning, quantization, system prompts); 3) Lower cost under high concurrency (token price is about 1/5 to 1/10 of the official API); 4) Controllable latency (intranet deployment, no public network latency); 5) No API call limits. Advantages of the official API: zero maintenance, full 671B model, low startup cost with pay-as-you-go. It is recommended to self-host for high-concurrency core business and use the official API for long-tail needs.

DeepSeek Complete Tutorial System

Below are all the DeepSeek tutorials and tools we provide, covering a complete learning path from beginner to enterprise level.

每日精选 Skill 推荐,免费送到你邮箱

输入邮箱,每天接收一个精选 AI Agent 技能推荐。完全免费,持续更新。

完全免费,取消任意时间。我们不会发送垃圾邮件。