Bidding
Updated System Design for a Campaign Management System
Since the system updates campaign data once per day in the morning, we can optimize it for batch processing rather than real-time updates. Here’s an updated design focusing on the daily refresh and including a high-level architecture diagram description:
1. High-Level Design Overview
The system will:
- Add clients via APIs for Yandex Direct, Google Ads, Meta, VK, and MyTarget.
- Fetch campaign data for each client and store it.
- Perform daily updates in the morning to download all campaigns and targeting data.
- Store historical data for reports and analysis.
- Execute predefined rules for campaign activation, deactivation, or optimization.
- Store rules and apply them daily based on conditions (e.g., campaign budget, time of day).
2. System Components
-
API Integration Layer:
- Fetches campaign data from different advertising platforms (Yandex Direct, Google Ads, Meta, VK, and MyTarget).
- Uses scheduled batch processing to download data once every day in the morning.
-
Data Storage:
- Amazon RDS (PostgreSQL): Stores client data, campaign details, targeting, and rules.
- Amazon S3: Stores large historical reports and campaign performance data for long-term storage.
-
Processing Layer:
- AWS Lambda: Executes daily batch jobs for fetching campaign data and updating campaign rules.
- AWS Step Functions: Orchestrates batch workflows, handling API rate limits and retries for campaign data retrieval.
-
Rule Engine:
- Lambda will also handle rule execution daily based on the downloaded data. For example, rules for enabling/disabling campaigns based on conditions like time, budget, or other factors.
-
Data Analysis:
- Athena/Redshift Spectrum: Analyze historical campaign data stored in S3 without moving it to RDS, enabling quick report generation.
3. Detailed Data Flow
a. Client Addition
- A user provides API credentials for a specific platform (e.g., Yandex Direct, Google Ads).
- The system makes an initial API call to retrieve the list of campaigns and targeting data.
- Store campaigns, keywords, or behavioral targets in PostgreSQL.
b. Daily Data Sync (Morning Update)
- AWS Lambda is triggered every morning at a scheduled time (e.g., 6:00 AM) to initiate the daily data sync.
- AWS Step Functions orchestrates calls to the APIs of each ad platform to fetch updated campaign data for all 1000 clients.
- Campaign data is retrieved and stored in PostgreSQL, while large historical reports (up to 10 MB per campaign) are archived in Amazon S3.
c. Rule Execution
- After the data sync, AWS Lambda checks for rules in the Rules Table. Rules can include conditions like:
- Enable/disable campaigns if the budget is above or below a certain threshold.
- Enable/disable campaigns based on the current date.
- Lambda updates campaign status in PostgreSQL according to these rules.
d. Historical Data Storage
- Campaign data before the update is archived in Amazon S3 to maintain a history.
- Athena/Redshift Spectrum allows users to run SQL-like queries over historical campaign data directly in S3.
4. System Scaling Considerations
- Batch Processing: Since updates are only required once a day, the system can handle the API load in batch mode. It does not need to process real-time data, reducing complexity.
- Storage: With large volumes of historical data (potentially 1 TB per year), using S3 for archival storage is cost-effective. RDS stores only active campaign data for fast access.
- Scaling AWS Components:
- Lambda and Step Functions scale automatically to handle the load of 1000 clients during the daily update.
- S3 provides virtually unlimited storage for historical reports and campaign data.
5. Database Schema
Campaign Table
| Field | Type | Description |
|---|---|---|
| campaign_id | UUID | Unique ID for each campaign |
| client_id | UUID | Foreign key to client |
| platform | Enum | Platform (Yandex, Google, Meta, etc.) |
| keywords | JSONB | List of keywords or behavioral targets |
| start_date | Timestamp | Start date of the campaign |
| end_date | Timestamp | End date of the campaign |
| status | Enum | Campaign status (active, paused, etc.) |
| daily_budget | Decimal | Daily budget for the campaign |
History Table
| Field | Type | Description |
|---|---|---|
| history_id | UUID | Unique ID for the historical record |
| campaign_id | UUID | Foreign key to campaign |
| change_timestamp | Timestamp | When the data was archived |
| data_snapshot | JSONB | Snapshot of the campaign's data at this time |
Rules Table
| Field | Type | Description |
|---|---|---|
| rule_id | UUID | Unique ID for each rule |
| condition | JSONB | Rule conditions (e.g., budget threshold, time) |
| action | JSONB | Action to take when condition is met |
| campaign_id | UUID | Foreign key to campaign |
6. High-Level Architecture Diagram (Textual Description)
- Client: Adds API credentials through the web interface.
- API Integration Layer: The integration layer fetches campaign data for Yandex Direct, Google Ads, Meta, VK, and MyTarget. This data is sent to the storage layer.
- Processing Layer: AWS Lambda functions handle the daily syncing of campaigns and rule execution. AWS Step Functions coordinate the API calls.
- Data Storage:
- RDS stores active campaign data, including keywords, budgets, and targeting information.
- S3 archives historical campaign data and performance reports.
- Rule Engine: Rules are stored in RDS and executed via Lambda after syncing campaigns.
- Data Analytics: Historical campaign data stored in S3 is queried using Athena or Redshift Spectrum for reporting purposes.
7. Technologies Used:
- API Integration: Custom connectors to Yandex Direct, Google Ads, Meta, VK, MyTarget APIs.
- Storage: PostgreSQL (Amazon RDS) for structured data, Amazon S3 for large historical data.
- Processing: AWS Lambda, AWS Step Functions for batch processing and rules.
- Querying: Amazon Athena or Redshift Spectrum for querying historical data in S3.
- Scheduling: AWS CloudWatch for scheduling daily Lambda triggers.
Таймеры и выполнение
Для того чтобы таймеры из правил могли достигать конечного API и выполнять операции, такие как отключение рекламных кампаний (РК), предлагается использовать комбинацию событийного подхода с функциями AWS Lambda. Вот как это может быть реализовано:
1. Правила с таймерами для РК
Правила для управления кампаниями по времени или по условиям могут включать, например:
- Отключение кампании в определённое время (например, 9:00 утра).
- Отключение кампании при достижении определённого лимита бюджета.
Эти правила будут храниться в таблице правил в базе данных (RDS). Структура таблицы правил уже приведена, но дополним её для работы с таймерами.
Пример схемы для таблицы правил:
| Поле | Тип | Описание |
|---|---|---|
| rule_id | UUID | Уникальный ID для каждого правила |
| campaign_id | UUID | ID рекламной кампании, к которой применимо правило |
| action_type | String | Тип действия (включение, отключение, корректировка бюджета) |
| condition | JSONB | Условия, такие как время выполнения или бюджет |
| execution_time | Timestamp | Время выполнения действия |
2. Механизм таймеров и выполнения правил
a. Запуск выполнения правил по расписанию (таймеры):
-
AWS EventBridge (ранее Amazon CloudWatch Events) будет использоваться для создания расписания выполнения правил.
- EventBridge позволяет настроить крон-выражения или фиксированные интервалы времени для выполнения определённых событий. Например, вы можете создать правило, которое будет запускать проверку всех правил в базе данных каждые 10 минут или в любое другое время.
-
AWS Lambda: В EventBridge настраивается правило, которое раз в заданный интервал вызывает функцию Lambda. Lambda обращается к базе данных, извлекает все правила с истёкшим временем выполнения (текущие таймеры) и проверяет, какие действия необходимо выполнить.
b. Выполнение действия из правил:
- AWS Lambda запускается по расписанию и проверяет в базе данных правила, которые нужно выполнить (например, если время
execution_timeправила уже наступило). - Lambda извлекает все подходящие правила с условиями и действиями, которые необходимо выполнить, такие как отключение рекламных кампаний.
- Для выполнения действия, например, отключения РК, Lambda вызывает API соответствующей рекламной платформы (например, Google Ads API или Yandex Direct API).