Technical Documentation: rudderlabs/rudder-server
โน๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference
Overview (`README.md`)
As the leading open source Customer Data Platform (CDP), RudderStack provides data pipelines that make it easy to collect data from every application, website and SaaS platform, then activate it in your warehouse and business tools.
With RudderStack, you can build customer data pipelines that connect your whole customer data stack and then make them smarter by triggering enrichment and activation in customer tools based on analysis in your data warehouse. It's easy-to-use SDKs and event source integrations, Cloud Extract integrations, transformations, and expansive library of destination and warehouse integrations makes building customer data pipelines for both event streaming and cloud-to-warehouse ELT simple.
| Try RudderStack Cloud Free - a free tier of RudderStack Cloud. Click here to start building a smarter customer data pipeline today, with RudderStack Cloud. |
|---|
Key features
Warehouse-first: RudderStack treats your data warehouse as a first class citizen among destinations, with advanced features and configurable, near real-time sync.
Developer-focused: RudderStack is built API-first. It integrates seamlessly with the tools that the developers already use and love.
High Availability: RudderStack comes with at least 99.99% uptime. We have built a sophisticated error handling and retry system that ensures that your data will be delivered even in the event of network partitions or destinations downtime.
Privacy and Security: You can collect and store your customer data without sending everything to a third-party vendor. With RudderStack, you get fine-grained control over what data to forward to which analytical tool.
Unlimited Events: Event volume-based pricing of most of the commercial systems is broken. With RudderStack Open Source, you can collect as much data as possible without worrying about overrunning your event budgets.
Segment API-compatible: RudderStack is fully compatible with the Segment API. So you don't need to change your app if you are using Segment; just integrate the RudderStack SDKs into your app and your events will keep flowing to the destinations (including data warehouses) as before.
Production-ready: Companies like Mattermost, IFTTT, Torpedo, Grofers, 1mg, Nana, OnceHub, and dozens of large companies use RudderStack for collecting their events.
Seamless Integration: RudderStack currently supports integration with over 90 popular tool and warehouse destinations.
User-specified Transformation: RudderStack offers a powerful JavaScript-based event transformation framework which lets you enhance or transform your event data by combining it with your other internal data. Furthermore, as RudderStack runs inside your cloud or on-premise environment, you can easily access your production data to join with the event data.
Get started
The easiest way to experience RudderStack is to sign up for RudderStack Cloud Free - a completely free tier of RudderStack Cloud.
You can also set up RudderStack on your platform of choice with these two easy steps:
Step 1: Set up RudderStack
Note: If you are planning to use RudderStack in production, we STRONGLY recommend using our Kubernetes Helm charts. We update our Docker images with bug fixes much more frequently than our GitHub repo.
Step 2: Verify the installation
Once you have installed RudderStack, send test events to verify the setup.
Architecture
RudderStack is an independent, stand-alone system with a dependency only on the database (PostgreSQL). Its backend is written in Go with a rich UI written in React.js.
A high-level view of RudderStackโs architecture is shown below:
For more details on the various architectural components, refer to our documentation.
Contribute
We would love to see you contribute to RudderStack. Get more information on how to contribute here.
License
RudderStack server is released under the Elastic License 2.0.
Overview (`regulation-worker/README.md`)
Set the following appropriately before running regulation-worker:-
- CONFIG_BACKEND_URL
- WORKSPACE_TOKEN (workspace secret: only required for single-tenant)
- WORKSPACE_NAMESPACE (namespace secret: only required for multi-tenant)
- DEST_TRANSFORM_URL (transformer url required to make downstream API call to destionations of API type.)
Overview (`suppression-backup-service/README.md`)
suppression-backup-service can be used to speed-up loading of suppression regulation at gateway after it's restart.
It regularly syncs with suppression-service & then creates latest and full backuped badgerdb, which are served from following endpoints:-
1. /full-export
this endpoint returns the full backup of suppression regulation till date.
2. /latest-export
As the above data might be really large and a little less relevant, so this endpoint returns suppression data of last 30 days.
To run this service following envs are requried:-
- WORKSPACE_TOKEN #workspace secret is required only in case single tenant.
- HOSTED_SERVICE_SECRET #namespace secret is required only in case of multi-tenant.
- CONFIG_BACKEND_URL #url to hit for getting config
SUPPRESS_USER_BACKEND_URL #url to hit for getting regulation-manager
Overview (`cmd/devtool/README.md`)
Rudder server devtool
This tool contains several commands to assist in running, debugging and manually testing rudder-server in a local environment.
etcd
etcd is a crucial component when running rudder-server in normal mode. Using the script you can:
- switch between normal and degraded mode of rudder-server
- change the workspace the server is responsible for
- wait for changes to be ack, or not using --no-wait
- list all the keys of etcd for debugging
event
You can send events to a running rudder server.
WEBHOOK
Simulates a destination.
Overview (`services/oauth/README.md`)
OAuth Module (services/oauth)
This module provides RudderStack's unified OAuth implementation and shared HTTP client used by Router Transformer, the Regulation Service and the Async destinations.
Important notes:
- Only one version of OAuth implementation exists now.
- Thereโs a single HTTP client handling both OAuth and nonโOAuth integrations from Router Transformer, Regulation Service and Async destinations.
Overview
The active implementation lives under services/oauth/v2. It exposes:
- A shared HTTP transport that transparently augments requests for OAuth destinations.
- An
OAuthHandlerthat fetches and refreshes access tokens via Control Plane, with inโmemory caching and metrics. - Lightweight context helpers to pass destination info and secrets across the HTTP pipeline.
Primary consumers: Router Transformer and the Regulation Service.
Architecture and Components
v2/http/client.go:NewOAuthHttpClient: wraps a given*http.ClientwithOAuthTransport, enabling both OAuth and nonโOAuth requests.
v2/http/transport.go:OAuthTransport (http.RoundTripper): request/response interceptor.- Detects if the destination is OAuthโenabled for the current flow.
- Preโroundtrip: fetches token (or uses cache) and augments the request via
extensions.Augmenter. - Postโroundtrip: interprets destination responses, handles refreshโtoken and authโinactive cases and emits metrics.
v2/oauth.go:OAuthHandler: orchestration for token fetch/refresh, CP calls, cache, locking, and metrics.
v2/controlplane/cp_connector.go:Connector: thin client to Control Plane; adds basic auth, handles timeouts/retries metadata, normalizes responses.
v2/context/context.go:- Helpers to embed and retrieve
backendconfig.DestinationTand tokensecretoncontext.Context.
- Helpers to embed and retrieve
v2/utils.go,v2/types.go,v2/common/constants.go,v2/cache.go,v2/stats.go:- Shared types, constants, cache interface, and small utilities.
Request Lifecycle
- Caller constructs an
*http.Requestand attachesbackendconfig.DestinationTto the context. - The shared clientโs
OAuthTransportinspects whether the destination is OAuth for the given flow. - If nonโOAuth: the request is passed through unchanged.
- If OAuth:
- Preโroundtrip:
OAuthHandler.FetchTokenreturns an access token (from cache or CP). The request is augmented viaextensions.Augmenter. - Roundtrip: underlying transport executes the request.
- Postโroundtrip: response is parsed to detect
REFRESH_TOKENorAUTH_STATUS_INACTIVEcategories and react accordingly (refresh token, return actionable status codes to caller). A structured interceptor payload is set on the response body to communicate outcomes.
- Preโroundtrip:
Control Plane Contracts
- Token fetch/refresh:
POST {ConfigBEURL}/destination/workspaces/{workspaceId}/accounts/{accountId}/token- Request body may include
{ hasExpired, expiredSecret }when refreshing. - Response includes
secretwithexpirationDateand providerโspecific token JSON.
- Request body may include
Configuration
HttpClient.oauth.timeout: Control Plane connector timeout (default 30s).ConfigBEURL: derived viabackendconfig.GetConfigBackendURL()for Control Plane endpoints.- Expiration skew: optional override via
WithExpirationTimeDiffonOAuthHandler(defaults to 1m).
Public APIs and Extension Points
- Shared client:
v2/http.NewOAuthHttpClient(client, flow, tokenCache, backendConfig, getAuthErrorCategory, args)returns a single client usable for both OAuth and nonโOAuth destinations.
- Transport:
OAuthTransportis injected intoclient.Transportand handles all OAuth logic.
- OAuth orchestration:
OAuthHandlermethods:FetchToken,RefreshToken.
- Extensions:
extensions.Augmenteraugments requests with providerโspecific auth material from the retrievedsecret.
Usage Example (Sketch)
// Build a single client for both OAuth and nonโOAuth destinations
baseClient := &http.Client{ Transport: http.DefaultTransport }
client := v2http.NewOAuthHttpClient(
baseClient,
common.RudderFlowDelivery,
tokenCache,
backendConfig,
detectAuthCategory, // func([]byte)(string, error) parsing destination response
&v2http.HttpClientOptionalArgs{ Logger: logger, Locker: locker },
)
// Attach destination info to context
ctx := oauthctx.CtxWithDestination(context.Background(), &backendconfig.DestinationT{ /* ... */ })
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, url, body)
// Perform request; transport transparently handles OAuth
resp, err := client.Do(req)Observability
- The module emits timers and counters for CP requests, total roundtrip latency, pre/post roundtrip phases, and outcome categories. Labels include flow, destination ID/type, workspace, and status codes.
Troubleshooting
- NonโOAuth destination: ensure
definition.auth.typeis absent or notOAuthfor passโthrough. - Missing account ID:
GetAccountIDvalidates expected keys per flow. - Token refresh loops: verify
expirationDateand augmentation; check Control Plane response and interceptor payload.
Maintenance
- Single version policy: only
v2is active; new functionality should extendv2. - Shared client: do not fork per consumer; extend transport/augmenters when needed.
Overview (`utils/wrk/README.md`)
- Install wrk
- Generate Basic Authorization Header
echo -n <your_write_key>: | openssl base64- Replace the above value for base64 encoded header `` in the
post.luascript - Run the load test
wrk -t100 -c100 -d120s -s post.lua http://localhost:8080/v1/batchOverview (`router/batchrouter/asyncdestinationmanager/README.md`)
AsyncDestinationManager
This document explains how the AsyncDestinationManager works in RudderStack's batch router and provides a comprehensive guide for onboarding new integrations.
Table of Contents
- Overview
- Architecture
- Core Interfaces
- Integration Types
- Onboarding New Integrations
- Implementation Patterns
- Testing Guidelines
- Configuration
- Examples
Overview
AsyncDestinationManager is a framework within RudderStack's batch router that handles asynchronous data uploads to external destinations. It provides a standardized interface for destinations that require:
- Bulk data uploads (CSV, JSON files)
- Asynchronous processing (polling for completion status)
- Complex authentication (OAuth, token management)
- File-based transfers (SFTP, cloud storage)
The framework abstracts the complexity of async operations while providing hooks for destination-specific customization.
Architecture
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโ
โ BatchRouter โโโโโถโ AsyncDestinationMgr โโโโโถโ Destination APIs โ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโ
โ File Storage โ
โ (Temp files, etc.) โ
โโโโโโโโโโโโโโโโโโโโโโโโKey Components
- AsyncDestinationManager Interface: Core contract that all integrations must implement
- Manager Factory: Routes destination types to their specific implementations
- Common Utilities: Shared functionality for file handling, configuration, etc.
- Integration Implementations: Destination-specific logic
Core Interfaces
AsyncDestinationManager
The main interface that all integrations must implement:
type AsyncDestinationManager interface {
AsyncUploadAndTransformManager
Poll(pollInput AsyncPoll) PollStatusResponse
GetUploadStats(UploadStatsInput GetUploadStatsInput) GetUploadStatsResponse
}
type AsyncUploadAndTransformManager interface {
Upload(asyncDestStruct *AsyncDestinationStruct) AsyncUploadOutput
Transform(job *jobsdb.JobT) (string, error)
}Key Methods
- Transform: Converts job data into the format expected by the destination
- Upload: Handles the actual data upload to the destination
- Poll: Checks the status of ongoing upload operations
- GetUploadStats: Retrieves detailed statistics about upload results
Integration Types
1. Regular Async Destinations
Destinations that require complex polling and status checking:
- Marketo Bulk Upload
- Bing Ads (Audience & Offline Conversions)
- Eloqua
- Yandex Metrica
- Klaviyo Bulk Upload
- Snowpipe Streaming
2. SFTP Destinations
File-based destinations that use SFTP protocol:
- SFTP (generic file transfer)
3. Simple Async Destinations
Destinations that don't require complex polling (using SimpleAsyncDestinationManager):
- Lytics Bulk Upload
- BigQuery Streaming
Onboarding New Integrations
Step 1: Determine Integration Type
Choose the appropriate integration pattern:
- Complex Async: Requires polling, status checking, detailed error handling
- Simple Async: Basic upload with immediate completion
- SFTP: File-based transfer using SFTP protocol
Step 2: Create Integration Directory
Create a new directory under asyncdestinationmanager/:
asyncdestinationmanager/
โโโ your-destination/
โโโ manager.go # Main manager implementation
โโโ types.go # Data structures
โโโ your-destination.go # Core logic
โโโ utils.go # Helper functions (optional)
โโโ testdata/ # Test files
โโโ your-destination_test.goStep 3: Implement Required Files
manager.go
package yourdestination
import (
"github.com/rudderlabs/rudder-go-kit/logger"
"github.com/rudderlabs/rudder-go-kit/stats"
backendconfig "github.com/rudderlabs/rudder-server/backend-config"
"github.com/rudderlabs/rudder-server/router/batchrouter/asyncdestinationmanager/common"
)
func NewManager(logger logger.Logger, statsFactory stats.Stats, destination *backendconfig.DestinationT) (common.AsyncDestinationManager, error) {
// Parse destination config
// Initialize API clients
// Return your manager implementation
}types.go
package yourdestination
// Define your destination-specific types
type DestinationConfig struct {
ApiKey string `json:"apiKey"`
BaseURL string `json:"baseUrl"`
// Add other config fields
}
type UploadResponse struct {
ImportID string `json:"importId"`
Status string `json:"status"`
}Step 4: Implement Core Interface
Choose one of these patterns:
Pattern A: Full AsyncDestinationManager Implementation
type YourDestinationManager struct {
logger logger.Logger
statsFactory stats.Stats
config DestinationConfig
// Add other fields
}
func (m *YourDestinationManager) Transform(job *jobsdb.JobT) (string, error) {
// Convert job payload to your destination format
return common.GetMarshalledData(string(job.EventPayload), job.JobID)
}
func (m *YourDestinationManager) Upload(asyncDestStruct *common.AsyncDestinationStruct) common.AsyncUploadOutput {
// Implement upload logic
// Return appropriate AsyncUploadOutput
}
func (m *YourDestinationManager) Poll(pollInput common.AsyncPoll) common.PollStatusResponse {
// Check upload status using pollInput.ImportId
// Return status response
}
func (m *YourDestinationManager) GetUploadStats(input common.GetUploadStatsInput) common.GetUploadStatsResponse {
// Parse upload results and return detailed statistics
}Pattern B: Simple Implementation (for fire-and-forget destinations)
func NewManager(logger logger.Logger, statsFactory stats.Stats, destination *backendconfig.DestinationT) (common.AsyncDestinationManager, error) {
uploader, err := NewYourDestinationUploader(logger, statsFactory, destination)
if err != nil {
return nil, err
}
return common.SimpleAsyncDestinationManager{UploaderAndTransformer: uploader}, nil
}Step 5: Register in Manager Factory
Add your destination to asyncdestinationmanager/manager.go:
// In utils.go, add to the appropriate slice
var asyncDestinations = []string{
// ... existing destinations
"YOUR_DESTINATION_NAME",
}
// In manager.go, add to newRegularManager function
func newRegularManager(...) (common.AsyncDestinationManager, error) {
switch destination.DestinationDefinition.Name {
// ... existing cases
case "YOUR_DESTINATION_NAME":
return yourdestination.NewManager(conf, logger, statsFactory, destination, backendConfig)
}
}Step 6: Add Tests
Create comprehensive tests following the warehouse testing guidelines:
func TestYourDestinationManager(t *testing.T) {
testCases := []struct {
name string
input InputType
expected ExpectedType
wantErr bool
}{
{
name: "successful upload",
input: validInput,
expected: expectedOutput,
wantErr: false,
},
// Add more test cases
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
// Test implementation
})
}
}Implementation Patterns
1. Configuration Parsing
func parseDestinationConfig(destination *backendconfig.DestinationT) (YourDestinationConfig, error) {
var config YourDestinationConfig
jsonConfig, err := jsonrs.Marshal(destination.Config)
if err != nil {
return config, fmt.Errorf("error marshalling destination config: %v", err)
}
err = jsonrs.Unmarshal(jsonConfig, &config)
if err != nil {
return config, fmt.Errorf("error unmarshalling destination config: %v", err)
}
return config, nil
}2. File Processing
func processUploadFile(filePath string) ([]YourDataType, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()
var data []YourDataType
scanner := bufio.NewScanner(file)
for scanner.Scan() {
var item YourDataType
if err := jsonrs.Unmarshal(scanner.Bytes(), &item); err != nil {
return nil, err
}
data = append(data, item)
}
return data, scanner.Err()
}3. Error Handling
func (m *YourDestinationManager) Upload(asyncDestStruct *common.AsyncDestinationStruct) common.AsyncUploadOutput {
// ... upload logic
if err != nil {
return common.AsyncUploadOutput{
FailedJobIDs: append(asyncDestStruct.FailedJobIDs, asyncDestStruct.ImportingJobIDs...),
FailedReason: fmt.Sprintf("Upload failed: %v", err),
FailedCount: len(asyncDestStruct.FailedJobIDs) + len(asyncDestStruct.ImportingJobIDs),
DestinationID: asyncDestStruct.Destination.ID,
}
}
// Success case
return common.AsyncUploadOutput{
ImportingJobIDs: asyncDestStruct.ImportingJobIDs,
ImportingParameters: getImportingParameters(importID),
ImportingCount: len(asyncDestStruct.ImportingJobIDs),
DestinationID: asyncDestStruct.Destination.ID,
}
}4. Polling Implementation
func (m *YourDestinationManager) Poll(pollInput common.AsyncPoll) common.PollStatusResponse {
status, err := m.apiService.GetImportStatus(pollInput.ImportId)
if err != nil {
return common.PollStatusResponse{
StatusCode: http.StatusInternalServerError,
Error: err.Error(),
}
}
switch status.State {
case "completed":
return common.PollStatusResponse{
StatusCode: http.StatusOK,
Complete: true,
}
case "failed":
return common.PollStatusResponse{
StatusCode: http.StatusOK,
HasFailed: true,
Error: status.ErrorMessage,
}
default:
return common.PollStatusResponse{
StatusCode: http.StatusOK,
InProgress: true,
}
}
}Testing Guidelines
Follow the warehouse testing guidelines:
- Use
requirefor assertions:require.NoError(t, err) - Table-driven tests for multiple scenarios
- Parallel execution: Use
t.Parallel()where safe - Proper cleanup: Use
t.Cleanup()for resource cleanup - Mock external services: Use gomock for API interactions
Example Test Structure
func TestYourDestination_Upload(t *testing.T) {
testCases := []struct {
name string
setupMock func(*MockAPIService)
asyncDestStruct *common.AsyncDestinationStruct
expectedOutput common.AsyncUploadOutput
}{
{
name: "successful upload",
setupMock: func(mock *MockAPIService) {
mock.EXPECT().Upload(gomock.Any()).Return("import-123", nil)
},
// ... test data
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockAPI := NewMockAPIService(ctrl)
tc.setupMock(mockAPI)
manager := &YourDestinationManager{
apiService: mockAPI,
// ... other fields
}
result := manager.Upload(tc.asyncDestStruct)
require.Equal(t, tc.expectedOutput, result)
})
}
}Configuration
Destination-Specific Config
Use the config utilities for destination-specific settings:
// Get destination-specific or fallback to global config
fileSizeLimit := common.GetBatchRouterConfigInt64("MaxUploadLimit", destName, 32*bytesize.MB)
retryCount := common.GetBatchRouterConfigInt64("maxRetries", destName, 3)Environment Variables
Follow the pattern: BatchRouter.DESTINATION_NAME.configKey
Example:
BatchRouter.MARKETO_BULK_UPLOAD.maxRetriesBatchRouter.ELOQUA.MaxUploadLimit
Examples
Complete Simple Implementation
See sftp/manager.go for a complete example of a simple async destination.
Complete Complex Implementation
See marketo-bulk-upload/ for a full-featured async destination with:
- Complex API interactions
- CSV file generation
- Polling with detailed status
- Error handling and statistics
API Service Pattern
See klaviyobulkupload/apiService.go for an example of separating API interactions into a dedicated service.
Best Practices
- Error Handling: Always provide detailed error messages with context
- Logging: Use structured logging with appropriate log levels
- Metrics: Emit relevant metrics for monitoring and debugging
- Resource Cleanup: Always clean up temporary files and connections
- Configuration: Use the common config utilities for consistency
- Testing: Write comprehensive tests covering success and failure scenarios
- Documentation: Document any destination-specific requirements or limitations
Troubleshooting
Common Issues
- Import not registered: Ensure your destination is added to
manager.go - Config parsing errors: Verify your config struct matches the destination configuration
- File handling issues: Always use proper file cleanup with
deferort.Cleanup() - Authentication failures: Check API key handling and token refresh logic
- Polling timeouts: Implement appropriate timeout handling in polling logic
Debugging Tips
- Enable debug logging: Set log level to debug for detailed operation logs
- Check file contents: Verify the format of generated upload files
- Monitor metrics: Use the emitted metrics to track upload success/failure rates
- Test with small batches: Start with small data sets to verify the integration works
Migration from Legacy Destinations
If migrating an existing destination to AsyncDestinationManager:
- Identify the current upload pattern (sync vs async)
- Extract configuration parsing logic
- Separate file generation from upload logic
- Implement the AsyncDestinationManager interface
- Add comprehensive tests
- Update destination routing in the manager factory
For questions or issues with AsyncDestinationManager integrations, refer to existing implementations in the asyncdestinationmanager/ directory or consult the team documentation.
Warehouse .Cursor Docs Snowpipe Streaming (`warehouse/.cursor/docs/snowpipe-streaming.md`)
Snowpipe Streaming in RudderStack
Overview
Snowpipe Streaming is RudderStack's mechanism for efficiently uploading and tracking data batches to Snowflake using the Snowpipe Streaming API. It handles event grouping, channel management, error handling, and polling for job completion.
Main Flow
1. Uploading Events
- Event File Created: Events are written to a file for batch upload.
- Manager.Upload: The upload process is initiated, reading events from the file.
- Grouping: Events are grouped by their target table.
- Channel Preparation: For each table, a channel is created (or reused) using
initializeChannelWithSchema(which internally callscreateChannel). - Event Insertion: Events are inserted into the channel via the Snowpipe Streaming API.
- Discards: Invalid or unprocessable events are sent to a discards table.
- Result: The upload returns lists of importing and failed job IDs, along with import parameters for polling.
2. Polling for Status
- Poll: The system periodically checks the status of each import using the import ID.
- getImportStatus: For each channel, the status is fetched via the API. If the channel is missing (e.g., due to a Snowpipe restart), it is recreated (without schema changes) and polling continues.
- Completion: Once all jobs reach a terminal state (success or failure), results are aggregated and returned.
3. Error Handling
- Auth/Backoff: If authentication or authorization errors occur, backoff logic is triggered to avoid repeatedly waking up the warehouse.
- Channel Recreation: If a channel is not found, it is recreated as needed for the operation to continue.
- Cleanup: Failed imports trigger channel cleanup and statistics updates.
Key Components
- Manager.Upload: Orchestrates the upload process, event grouping, and channel management.
- initializeChannelWithSchema: Ensures the channel exists and schema is up to date (not used during polling recreation).
- createChannel: Handles channel creation and cache updates.
- getImportStatus: Polls for job status, recreates channels if needed, and updates cache.
- Backoff Logic: Prevents repeatedly waking up the warehouse when persistent errors occur.
References
- See
router/batchrouter/asyncdestinationmanager/snowpipestreaming/snowpipestreaming.gofor main logic. - See
router/batchrouter/asyncdestinationmanager/snowpipestreaming/channel.gofor channel management details.
Warehouse .Cursor Docs Staging File Flow (`warehouse/.cursor/docs/staging-file-flow.md`)
Staging File Flow and Field Propagation
This document explains how staging files flow through the RudderStack warehouse service and how to add new fields to staging file payloads.
Flow Architecture
The staging file flow follows a clear data pipeline across warehouse system components:
[Batch Router] โ [Warehouse Client] โ [Warehouse API] โ [Model/Repo] โ [Database]
โณ POST /v1/process โEach component has distinct responsibilities and transformation points that must be considered when adding new fields.
Component Responsibilities
Batch Router: Origin and Data Generation
Responsibility: Creates staging file payload after uploading data to object storage
Key Points:
- All new fields must be populated here from available data sources
- Values originate from job parameters, environment state, or system context
- This is the single source of truth for field values
- Calls warehouse API endpoint
POST /v1/processto notify about new staging files
Warehouse Client: Transport and Conversion
Responsibility: Converts staging files to HTTP payload format for inter-service communication
Key Points:
- Handles structural transformation between internal and transport formats
- Passes fields through without modification or value generation
- Requires mapping between input and payload structures
Warehouse API: Request Processing
Responsibility: Receives HTTP requests and maps them to internal data models
Key Points:
- Unmarshals transport payloads into internal representations
- Validates incoming data structure and format
- Bridges external interface with internal architecture
Model/Repo: Data Structure and Persistence
Responsibility: Defines canonical staging file structure and manages database operations
Key Points:
- Model establishes the authoritative data schema and handles type safety
- Repository persists field metadata through JSON serialization in metadata column
- Handles schema evolution, backward compatibility, and data retrieval operations
Implementation Checklist
When adding new fields to staging file payloads, ensure coverage across all warehouse components:
Warehouse Client Updates
- Add field to staging file input structure
- Add field to HTTP payload structure
- Implement field mapping from input to payload
Warehouse API Updates
- Add field to incoming request schema
- Update mapping functions to internal model
- Validate field format and constraints
Model/Repository Updates
- Add field to model structure
- Define field in metadata schema with JSON tags
- Update metadata conversion functions for persistence
Batch Router Integration
- Set field value in batch router's warehouse notification
- Verify field population across all staging file creation points
- Use appropriate data sources for field value generation
Testing Coverage
- Update test fixtures and staging file creation helpers
- Verify end-to-end field propagation in integration tests
- Test metadata serialization and deserialization cycles
Key Architectural Concepts
Metadata Persistence Strategy
Most staging file fields are stored as JSON within a metadata column, requiring:
- Serialization: Converting model structures to JSON format
- Deserialization: Reconstructing models from stored JSON
- Schema Evolution: Handling field additions without breaking existing data
Data Flow Separation
The architecture maintains clear separation of concerns:
- Value Generation: Occurs only in batch router
- Value Transport: Warehouse client moves data without modification
- Value Validation: Warehouse API ensures data integrity
- Value Persistence: Repository handles storage mechanics
Backward Compatibility Requirements
New field implementations must:
- Provide sensible defaults for missing values
- Handle graceful degradation when fields are absent
- Consider future evolution paths for field requirements
Common Implementation Pitfalls
- Incomplete Batch Router Population: Field structure exists but values are not set in batch router
- Misplaced Value Generation: Attempting to fetch or compute values in warehouse client instead of batch router
- Broken Metadata Flow: Field reaches model but persistence conversion is incomplete
- Test-Only Implementation: Field works in test environment but fails in production data flow
Reference Implementation Patterns
For consistent implementation approaches:
- Follow established patterns from existing staging file fields
- Maintain architectural layer separation used in current implementations
- Apply the same metadata persistence strategies for similar data types
File Organization Reference
| Component | Primary Focus | Implementation Scope |
|---|---|---|
| Batch Router | Data generation and context capture | Batch processing and initial payload creation |
| Warehouse Client | Inter-service communication | HTTP transport and format conversion |
| Warehouse API | Request handling and validation | Incoming data processing and routing |
| Model/Repo | Data representation and persistence | Core business logic, data structures, and database operations |
| Test Infrastructure | Development and validation support | Test utilities and verification helpers |
This architectural approach ensures staging file metadata accurately captures processing context for comprehensive traceability and effective debugging across the warehouse service.
--- METRICS ---
- Files Extracted: 9
- Estimated Token Budget: ~9671 tokens
- Canonical Reference: https://codewiki.google/github.com/rudderlabs/rudder-server