rudder-server Documentation

Privacy and Security focused Segment-alternative, in Golang and React

RAW Doc

Docker & Self-Hosted Deployment Verified OCI

Deploy rudder-server on any server, homelab, or cloud container platform.

1-Click Terminal Command
bash (docker run)
docker run -d --name rudder-server -p 9090:9090 --restart always rudderstack/rudder-transformer:latest
Configured Services & Ports
โš™๏ธ transformer
image: rudderstack/rudder-transformer:latest
๐Ÿ”Œ Ports: 9090:9090
docker-compose.yml
yaml (docker-compose.yml)
version: "3.9"

services:
  transformer:
    image: "rudderstack/rudder-transformer:latest"
    ports:
      - "9090:9090"
    healthcheck:
      test: wget --no-verbose --tries=1 --spider http://0.0.0.0:9090/health || exit 1
      interval: 1s
      retries: 25

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:-

  1. CONFIG_BACKEND_URL
  2. WORKSPACE_TOKEN (workspace secret: only required for single-tenant)
  3. WORKSPACE_NAMESPACE (namespace secret: only required for multi-tenant)
  4. 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:-

  1. WORKSPACE_TOKEN #workspace secret is required only in case single tenant.
  2. HOSTED_SERVICE_SECRET #namespace secret is required only in case of multi-tenant.
  3. 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 OAuthHandler that 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.Client with OAuthTransport, 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.DestinationT and token secret on context.Context.
  • 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

  1. Caller constructs an *http.Request and attaches backendconfig.DestinationT to the context.
  2. The shared clientโ€™s OAuthTransport inspects whether the destination is OAuth for the given flow.
  3. If nonโ€‘OAuth: the request is passed through unchanged.
  4. If OAuth:
    • Preโ€‘roundtrip: OAuthHandler.FetchToken returns an access token (from cache or CP). The request is augmented via extensions.Augmenter.
    • Roundtrip: underlying transport executes the request.
    • Postโ€‘roundtrip: response is parsed to detect REFRESH_TOKEN or AUTH_STATUS_INACTIVE categories and react accordingly (refresh token, return actionable status codes to caller). A structured interceptor payload is set on the response body to communicate outcomes.

Control Plane Contracts

  • Token fetch/refresh: POST {ConfigBEURL}/destination/workspaces/{workspaceId}/accounts/{accountId}/token
    • Request body may include { hasExpired, expiredSecret } when refreshing.
    • Response includes secret with expirationDate and providerโ€‘specific token JSON.

Configuration

  • HttpClient.oauth.timeout: Control Plane connector timeout (default 30s).
  • ConfigBEURL: derived via backendconfig.GetConfigBackendURL() for Control Plane endpoints.
  • Expiration skew: optional override via WithExpirationTimeDiff on OAuthHandler (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:
    • OAuthTransport is injected into client.Transport and handles all OAuth logic.
  • OAuth orchestration:
    • OAuthHandler methods: FetchToken, RefreshToken.
  • Extensions:
    • extensions.Augmenter augments requests with providerโ€‘specific auth material from the retrieved secret.

Usage Example (Sketch)

go
// 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.type is absent or not OAuth for passโ€‘through.
  • Missing account ID: GetAccountID validates expected keys per flow.
  • Token refresh loops: verify expirationDate and augmentation; check Control Plane response and interceptor payload.

Maintenance

  • Single version policy: only v2 is active; new functionality should extend v2.
  • Shared client: do not fork per consumer; extend transport/augmenters when needed.

Overview (`utils/wrk/README.md`)

  • Install wrk
  • Generate Basic Authorization Header
text
echo -n <your_write_key>: | openssl base64
  • Replace the above value for base64 encoded header `` in the post.lua script
  • Run the load test
text
wrk -t100 -c100 -d120s -s post.lua http://localhost:8080/v1/batch

Overview (`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

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:

  1. Bulk data uploads (CSV, JSON files)
  2. Asynchronous processing (polling for completion status)
  3. Complex authentication (OAuth, token management)
  4. File-based transfers (SFTP, cloud storage)

The framework abstracts the complexity of async operations while providing hooks for destination-specific customization.

Architecture

text
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   BatchRouter   โ”‚โ”€โ”€โ”€โ–ถโ”‚ AsyncDestinationMgr  โ”‚โ”€โ”€โ”€โ–ถโ”‚  Destination APIs   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                  โ”‚
                                  โ–ผ
                       โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                       โ”‚     File Storage     โ”‚
                       โ”‚  (Temp files, etc.) โ”‚
                       โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Key Components

  1. AsyncDestinationManager Interface: Core contract that all integrations must implement
  2. Manager Factory: Routes destination types to their specific implementations
  3. Common Utilities: Shared functionality for file handling, configuration, etc.
  4. Integration Implementations: Destination-specific logic

Core Interfaces

AsyncDestinationManager

The main interface that all integrations must implement:

go
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

  1. Transform: Converts job data into the format expected by the destination
  2. Upload: Handles the actual data upload to the destination
  3. Poll: Checks the status of ongoing upload operations
  4. 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/:

text
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.go

Step 3: Implement Required Files

manager.go

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

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

go
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)

go
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:

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:

go
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

go
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

go
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

go
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

go
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:

  1. Use require for assertions: require.NoError(t, err)
  2. Table-driven tests for multiple scenarios
  3. Parallel execution: Use t.Parallel() where safe
  4. Proper cleanup: Use t.Cleanup() for resource cleanup
  5. Mock external services: Use gomock for API interactions

Example Test Structure

go
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:

go
// 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.maxRetries
  • BatchRouter.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

  1. Error Handling: Always provide detailed error messages with context
  2. Logging: Use structured logging with appropriate log levels
  3. Metrics: Emit relevant metrics for monitoring and debugging
  4. Resource Cleanup: Always clean up temporary files and connections
  5. Configuration: Use the common config utilities for consistency
  6. Testing: Write comprehensive tests covering success and failure scenarios
  7. Documentation: Document any destination-specific requirements or limitations

Troubleshooting

Common Issues

  1. Import not registered: Ensure your destination is added to manager.go
  2. Config parsing errors: Verify your config struct matches the destination configuration
  3. File handling issues: Always use proper file cleanup with defer or t.Cleanup()
  4. Authentication failures: Check API key handling and token refresh logic
  5. Polling timeouts: Implement appropriate timeout handling in polling logic

Debugging Tips

  1. Enable debug logging: Set log level to debug for detailed operation logs
  2. Check file contents: Verify the format of generated upload files
  3. Monitor metrics: Use the emitted metrics to track upload success/failure rates
  4. 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:

  1. Identify the current upload pattern (sync vs async)
  2. Extract configuration parsing logic
  3. Separate file generation from upload logic
  4. Implement the AsyncDestinationManager interface
  5. Add comprehensive tests
  6. 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 calls createChannel).
  • 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.go for main logic.
  • See router/batchrouter/asyncdestinationmanager/snowpipestreaming/channel.go for 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:

text
[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/process to 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

  1. Incomplete Batch Router Population: Field structure exists but values are not set in batch router
  2. Misplaced Value Generation: Attempting to fetch or compute values in warehouse client instead of batch router
  3. Broken Metadata Flow: Field reaches model but persistence conversion is incomplete
  4. 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 ---