Skip to content

shreshta-p/microadserve-go

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MicroAdServe-Go

A lightweight, high-performance ad-serving engine demonstrating core ad-tech concepts including real-time ad ranking, impression tracking, metrics computation, and fraud detection.

What It Does

  • Selects the best-performing ad using a bid x CTR ranking algorithm
  • Records ad impressions with metadata (IP, timestamp, user-agent)
  • Computes real-time analytics over sliding time windows
  • Detects suspicious traffic patterns and fraud attempts

Architecture

Core Components

Ad Selection Engine: Ranks ads based on bid x CTR score to maximize revenue per impression.

Impression Tracker: Records each ad view with client metadata using thread-safe in-memory storage.

Metrics Aggregator: Computes real-time statistics over 60-second sliding windows including total impressions, impressions by ad, and requests per IP.

Fraud Detection: Identifies suspicious IPs with >20 requests/minute and calculates a fraud score (0-1) based on traffic concentration patterns.

API Endpoints

  • GET /ad - Returns the winning ad based on highest score
  • POST /impression - Records an ad impression
  • GET /metrics - Returns computed metrics and fraud detection results
  • GET /health - Health check endpoint
  • GET /ads - Returns all available ads
  • POST /ads/add - Adds a new ad
  • DELETE /ads/delete?id={ad_id} - Deletes an ad by ID

Web UI

  • / - Demo page showing live ad serving
  • /admin.html - Admin panel for managing ads
  • /dashboard.html - Analytics dashboard with real-time metrics

Tech Stack

  • Language: Go 1.21
  • Framework: net/http (standard library)
  • Concurrency: sync.Mutex for thread-safe operations
  • Storage: In-memory data structures
  • Containerization: Docker multi-stage builds

Prerequisites

  • Go 1.21 or later
  • Docker (optional, for containerized deployment)

Quickstart

Run Locally

cd microadserve-go
go run .

The server starts on port 8080. Access the web UI at http://localhost:8080

Build Binary

go build -o microadserve-go.exe .
./microadserve-go.exe

Test Endpoints

# Health check
curl http://localhost:8080/health

# Get best ad
curl http://localhost:8080/ad

# Record impression
curl -X POST http://localhost:8080/impression \
  -H "Content-Type: application/json" \
  -d '{"ad_id":"ad_2"}'

# View metrics
curl http://localhost:8080/metrics

Run with Docker

docker build -t microadserve-go .
docker run -p 8080:8080 microadserve-go

Note: The current Dockerfile does not copy the static directory. To fix this, add COPY --from=builder /app/static ./static before the CMD instruction.

Configuration

Environment Variables

  • PORT - Server port (default: 8080)

Default Ads

The server comes pre-configured with 4 sample ads:

  • Premium Cloud Hosting (bid: $2.50, CTR: 8%)
  • Learn Go Programming (bid: $1.80, CTR: 12%)
  • Best Coffee Maker 2025 (bid: $3.00, CTR: 5%)
  • Travel Deals (bid: $2.20, CTR: 9%)

How to Run Tests

Currently, this project does not include automated tests. Manual testing can be performed using the test-server.ps1 PowerShell script:

.\test-server.ps1

This script starts the server and tests all endpoints automatically.

Project Structure

microadserve-go/
├── main.go              # Complete server implementation
├── go.mod              # Go module definition
├── Dockerfile          # Multi-stage Docker build
├── .gitignore          # Git ignore rules
├── test-server.ps1     # PowerShell test script
├── static/             # Web UI files
│   ├── index.html      # Main demo page
│   ├── admin.html      # Admin panel
│   └── dashboard.html  # Analytics dashboard
└── archive/            # Archived documentation

Key Implementation Details

  • Thread Safety: Uses sync.Mutex to protect shared impression slice during concurrent writes
  • IP Extraction: Properly handles X-Forwarded-For headers for proxy/load balancer scenarios
  • Fraud Detection: Implements nuanced scoring that considers both percentage and absolute counts to avoid false positives during low-traffic periods
  • Ad Ranking: Simple but effective bid x CTR algorithm maximizes expected revenue

Troubleshooting

Server won't start

  • Check if port 8080 is already in use
  • Verify Go is properly installed: go version
  • Ensure you're in the correct directory with main.go

Static files not loading

  • Verify the static/ directory exists and contains HTML files
  • Check server logs for file serving errors
  • If using Docker, ensure the Dockerfile copies the static directory

High fraud scores with legitimate traffic

The fraud detection thresholds can be adjusted in the computeMetrics function:

  • IP threshold: Currently 20 requests/minute
  • Minimum traffic: 5 impressions before fraud scoring activates

Roadmap / Future Improvements

  • Add persistent storage (PostgreSQL, BigQuery) for production use
  • Implement distributed caching with Redis for multi-instance deployments
  • Add event streaming with Pub/Sub for real-time analytics
  • Create comprehensive unit and integration tests
  • Implement request rate limiting per IP
  • Add authentication and authorization for admin endpoints
  • Support for multiple ad formats (banner sizes, video, native)
  • A/B testing capabilities for ad creative optimization
  • Implement CTR prediction models using historical data
  • Add Prometheus metrics and Grafana dashboards

License

TBD

About

Lightweight ad-serving engine in Go with real-time bid×CTR ranking, IP-based fraud detection, and sliding window analytics. Pure Go stdlib implementation.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors