A Go service that performs user ID synchronization between an ad server and third-party buyers. It supports both iframe and chained redirect sync methods.
- Supports both iframe and chained redirect sync methods
- Redis-based storage for user ID mappings
- Cookie-based internal user ID management
- Concurrent-safe operations with optimized locking
- Graceful shutdown
- JSON-based configuration
- Performance optimizations for high throughput
- URL caching for reduced latency
- Connection pooling for better resource utilization
- Built-in test handler for buyer endpoint simulation
- Go 1.16 or later
- Redis server (required for storage)
brew install redis
brew services start redis
sudo apt update
sudo apt install redis-server
sudo systemctl start redis-server
- Download Redis for Windows from https://github.com/microsoftarchive/redis/releases
- Extract and run redis-server.exe
redis-cli ping
# Should return PONG
- Clone the repository:
git clone <repository-url>
cd ow_user_sync
- Install dependencies:
go mod tidy
The service is configured using a JSON file (config.json
) in cmd/server folder:
{
"server": {
"port": "8080",
"base_url": "http://localhost:8080",
"read_timeout": 10,
"write_timeout": 10,
"idle_timeout": 120
},
"redis": {
"address": "localhost:6379",
"password": "",
"db": 0,
"pool_size": 10
}
}
-
Server Settings
port
: Server port (default: "8080")base_url
: Base URL for callbacks (default: "http://localhost:8080")read_timeout
: Read timeout in seconds (default: 10)write_timeout
: Write timeout in seconds (default: 10)idle_timeout
: Idle timeout in seconds (default: 120)
-
Redis Settings
address
: Redis server address (default: "localhost:6379")password
: Redis password (default: "")db
: Redis database number (default: 0)pool_size
: Connection pool size (default: 10)
The buyers configuration is located in internal/config/buyers.go
. You can modify this file to:
- Add new buyers
- Change buyer URLs
- Test different buyer behaviors
Example buyer configuration:
var buyers = map[string]string{
"buyer1": "http://localhost:8081",
"buyer2": "http://localhost:8082",
"buyer3": "http://localhost:8083",
}
- Start the server:
go run cmd/server/main.go
- The service exposes the following endpoints:
GET /adserver/sync?type=iframe
: Returns HTML with iframes for each buyerGET /adserver/sync?type=img
: Starts chained redirects through buyers' sync URLsGET /adserver/sync-callback
: Stores buyer UIDs and continues redirect chainGET /adserver/get-uids
: Returns JSON of all buyer UIDs for the current user
The service includes a test handler at /test/
that simulates buyer endpoints for testing:
/test/buyer1
: Simulates buyer1's sync endpoint/test/buyer2
: Simulates buyer2's sync endpoint/test/buyer3
: Simulates buyer3's sync endpoint
Each test endpoint:
- Accepts a callback URL
- Generates a mock buyer UID
- Redirects to the callback URL with the UID
Important Note: When using the
img
endpoint, if the user's cookies are deleted, you must add a cache busting parameter (cb
) to the next request. This ensures the browser doesn't use a cached response. Example:# After deleting cookies, use: curl "http://localhost:8080/adserver/sync?type=img&cb=1234567890"
Example test flow:
# Start with iframe sync
curl "http://localhost:8080/adserver/sync?type=iframe"
# Or start with image sync
curl "http://localhost:8080/adserver/sync?type=img"
{
"userId": "abc123",
"buyerUids": {
"ttd": "xyz456",
"rubicon": "rubi888"
}
}
-
Concurrency Handling
- Uses RWMutex for better concurrent read performance
- Implements connection pooling for Redis
- Optimizes lock granularity for better throughput
-
Redis Optimizations
- Uses Redis pipelines for batch operations
- Implements connection pooling
- Configures timeouts and retries
- Uses TTL for automatic cleanup
The service can be split into microservices for better scalability:
-
User Sync Service
- Handles sync requests and redirects
- Manages user ID generation
- Can be scaled independently based on sync traffic
-
UID Storage Service
- Manages Redis operations
- Handles user ID mappings
- Can be scaled based on storage needs
-
Test Service
- Provides mock buyer endpoints
- Can be deployed separately for testing
Benefits of microservices:
- Independent scaling of components
- Better resource utilization
- Easier maintenance and updates
- Improved fault isolation
For global deployment, consider implementing edge caching:
-
CDN Integration
- Deploy CDN for static content
- Cache generated URLs at the edge
- Implement edge-side includes for dynamic content
-
Regional Deployment
- Deploy services in multiple regions
- Use regional Redis instances
- Implement geo-based routing
-
Load Balancing
- Use load balancers for traffic distribution
- Implement health checks
- Configure auto-scaling based on load
-
Load Balancing
- Deploy multiple instances behind a load balancer
- Use sticky sessions based on user ID for consistent routing
- Implement health checks for instance monitoring
-
Redis Cluster
- Use Redis Cluster for data sharding
- Implement read replicas for better read performance
- Configure automatic failover
-
Caching Layer
- Add a distributed cache (e.g., Memcached) for frequently accessed data
- Implement cache warming strategies
- Use cache invalidation patterns
-
Multi-Region Deployment
- Deploy instances in multiple regions
- Use geo-based DNS routing
- Implement region-aware Redis replication
-
Data Locality
- Store user data in the region closest to the user
- Implement cross-region data synchronization
- Use eventual consistency for better performance
-
Edge Caching
- Deploy CDN for static content
- Cache generated URLs at the edge
- Implement edge-side includes for dynamic content
-
Metrics Collection
- Track request latency
- Monitor Redis performance
- Measure cache hit rates
-
Logging
- Implement structured logging
- Use log aggregation
- Track error rates and types
-
Alerting
- Set up performance thresholds
- Monitor error rates
- Track resource utilization
The project follows a clean architecture with the following structure:
ow_user_sync/
├── cmd/
│ └── server/ # Server entry point
├── internal/
│ ├── handlers/ # HTTP handlers
│ ├── storage/ # Storage interface and Redis implementation
│ ├── config/ # Configuration
│ ├── cookies/ # Cookie management
│ └── utils/ # Utility functions
├── go.mod # Go module file
└── README.md # This file