Skip to main content

feldera_types/transport/
dynamodb.rs

1use crate::size::{ConfigSize, LegacySizeUnit};
2use serde::{Deserialize, Serialize};
3use utoipa::ToSchema;
4
5/// Connectors by default start with 1 worker thread.
6/// Increasing the number of threads helps scale the encoding process; however, for
7/// DynamoDB, encoding is often not the bottleneck, writing to DynamoDB is.
8fn default_threads() -> usize {
9    1
10}
11
12/// Ten retries with the ~13s backoff ceiling retry for roughly one minute:
13/// enough to ride out transient throttling, bounded enough not to stall the
14/// pipeline forever. Set `max_retries` to `null` for unbounded.
15fn default_max_retries() -> Option<u8> {
16    Some(10)
17}
18
19fn default_max_buffer_size() -> ConfigSize {
20    ConfigSize::from_mib(1)
21}
22fn schema_default_max_buffer_size() -> String {
23    default_max_buffer_size().to_string()
24}
25crate::required_size_setting!(
26    size_max_buffer_size,
27    "max_buffer_size",
28    LegacySizeUnit::Bytes
29);
30
31/// Number of concurrent requests made to DynamoDB at any time.
32/// Increasing this may improve the throughput, but may also cause
33/// throttling and increase retries.
34///
35/// 64 concurrent requests mean at any time, we submit a maximum of:
36/// - 64 * 25 Batch items
37/// - 64 * 100 Transactional items
38fn default_max_concurrent_requests() -> usize {
39    64
40}
41
42/// Batch mode allows for higher throughput than transactional mode.
43fn default_write_mode() -> DynamoDBWriteMode {
44    DynamoDBWriteMode::Batch
45}
46
47/// DynamoDB write API used by the output connector.
48#[derive(Debug, Clone, Copy, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
49#[serde(rename_all = "snake_case")]
50pub enum DynamoDBWriteMode {
51    /// Use DynamoDB [`BatchWriteItem`].
52    ///
53    /// This is the high-throughput path. Each request writes up to 25 items,
54    /// and each item costs one write capacity unit (WCU). Writes are flushed at
55    /// batch end, but DynamoDB does not make the whole batch atomic: some items
56    /// in a request may succeed while others fail (and are retried).
57    ///
58    /// [`BatchWriteItem`]: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchWriteItem.html
59    Batch,
60
61    /// Use DynamoDB [`TransactWriteItems`].
62    ///
63    /// This provides atomicity for each transaction chunk: either all items in
64    /// the request are written or none are. It is substantially slower than
65    /// `Batch` and is limited to 100 writes per request.
66    ///
67    /// [`TransactWriteItems`]: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_TransactWriteItems.html
68    Transactional,
69}
70
71/// DynamoDB output connector configuration.
72#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
73pub struct DynamoDBWriterConfig {
74    /// Name of the DynamoDB table to write to.
75    pub table: String,
76
77    /// AWS region.
78    pub region: String,
79
80    /// Optional endpoint URL, for example when using a local
81    /// DynamoDB-compatible service.
82    pub endpoint_url: Option<String>,
83
84    /// AWS access key ID.
85    ///
86    /// If both `aws_access_key_id` and `aws_secret_access_key` are specified,
87    /// the connector uses these static credentials. Otherwise it uses the
88    /// default AWS credential provider chain, including IAM Roles for Service
89    /// Accounts (IRSA) in EKS.
90    ///
91    /// Static credentials are treated as long-lived IAM keys: no session token
92    /// is sent, so STS-issued temporary credentials are not supported via these
93    /// fields. To use temporary credentials, rely on the default provider chain
94    /// instead (leave these unset).
95    pub aws_access_key_id: Option<String>,
96
97    /// AWS secret access key.
98    pub aws_secret_access_key: Option<String>,
99
100    /// Maximum number of write requests in one DynamoDB write call.
101    ///
102    /// DynamoDB supports at most 100 for `TransactWriteItems` and at most 25
103    /// for `BatchWriteItem`. If omitted, the connector uses the maximum for
104    /// the selected `write_mode`.
105    #[serde(default)]
106    pub batch_size: Option<usize>,
107
108    /// Write API to use when flushing records at batch end.
109    ///
110    /// The default is `batch`, where each worker bulk-writes its own split
111    /// using DynamoDB `BatchWriteItem`.
112    #[serde(default = "default_write_mode")]
113    #[schema(default = default_write_mode)]
114    pub write_mode: DynamoDBWriteMode,
115
116    /// Maximum size of the data buffered by each worker before flushing
117    /// writes, such as `"1Mi"`.
118    ///
119    /// This is an approximate size based on encoded DynamoDB attributes.
120    ///
121    /// Before release 0.367.0 this setting was `max_buffer_size_bytes`, a
122    /// number of bytes. That name is deprecated but still read.
123    #[serde(
124        default = "default_max_buffer_size",
125        alias = "max_buffer_size_bytes",
126        deserialize_with = "size_max_buffer_size"
127    )]
128    #[schema(value_type = String, default = schema_default_max_buffer_size)]
129    pub max_buffer_size: ConfigSize,
130
131    /// Maximum number of DynamoDB write requests in flight per worker thread.
132    ///
133    /// The total in-flight request count across the connector is
134    /// `threads × max_concurrent_requests`. Size this accordingly when
135    /// tuning against a provisioned-throughput table to avoid excessive
136    /// throttling.
137    #[serde(default = "default_max_concurrent_requests")]
138    #[schema(default = default_max_concurrent_requests)]
139    pub max_concurrent_requests: usize,
140
141    /// Number of worker threads used to encode and write disjoint key ranges.
142    #[serde(default = "default_threads")]
143    #[schema(default = default_threads)]
144    pub threads: usize,
145
146    /// Maximum number of retries of a DynamoDB write chunk after its first request.
147    ///
148    /// One budget covers every reason a chunk is sent again: items that a successful
149    /// `BatchWriteItem` response returns as unprocessed, a `TransactWriteItems` call cancelled by
150    /// transient contention, and a request that fails with a retryable error, such as
151    /// throttling, a timeout, a network failure, a server error, or a temporary failure to
152    /// obtain credentials. The AWS SDK makes its own few attempts first; only a retry that this
153    /// connector starts after the SDK gave up counts here. Each retry waits longer than the
154    /// previous one (exponential backoff with random jitter), up to a ceiling of roughly 13
155    /// seconds.
156    ///
157    /// `0` permits no retry. Set to `null` to retry indefinitely: the connector keeps retrying
158    /// at the ceiling interval, and the pipeline waits behind it, until DynamoDB recovers or
159    /// the pipeline stops. When a bounded budget runs out, the chunk's remaining records are
160    /// discarded and counted in `dynamodb_output_failed_items_total`.
161    ///
162    /// An error that a retry cannot fix, such as a validation error, a missing table, denied
163    /// access, or an invalid credential configuration, discards the chunk at once, whatever
164    /// the budget. Items of a transaction that fail their condition expression are dropped
165    /// without a retry, which costs nothing here.
166    ///
167    /// Once a chunk has retried for ten seconds, the connector reports itself unhealthy in
168    /// the pipeline's statistics, with the cause; it reports healthy again once no chunk
169    /// retries and a chunk has landed. Defaults to `10`.
170    #[serde(default = "default_max_retries")]
171    #[schema(default = default_max_retries)]
172    pub max_retries: Option<u8>,
173
174    /// [Condition expression] evaluated before each put (insert or upsert).
175    ///
176    /// When the condition is false, the record is skipped without failing the
177    /// connector. This option requires `transactional` [`write_mode`].
178    ///
179    /// The condition gates every value write, and the connector cannot tell a
180    /// replayed insert from a legitimate update: both arrive as puts. A guard
181    /// such as `attribute_not_exists(id)` therefore also suppresses updates to
182    /// existing keys, not just replayed duplicates. Choose the expression
183    /// accordingly.
184    ///
185    /// The connector does not currently support `ExpressionAttributeNames` or
186    /// `ExpressionAttributeValues`, so the expression cannot use placeholders.
187    ///
188    /// [Condition expression]: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html
189    /// [`write_mode`]: Self::write_mode
190    #[serde(default)]
191    pub put_condition_expression: Option<String>,
192
193    /// [Condition expression] evaluated before each delete.
194    ///
195    /// When the condition is false, the delete is skipped without failing the
196    /// connector. This option requires `transactional` [`write_mode`]. The
197    /// expression cannot use `ExpressionAttributeNames` or
198    /// `ExpressionAttributeValues` placeholders.
199    ///
200    /// [Condition expression]: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html
201    /// [`write_mode`]: Self::write_mode
202    #[serde(default)]
203    pub delete_condition_expression: Option<String>,
204}
205
206impl DynamoDBWriterConfig {
207    pub fn effective_batch_size(&self) -> usize {
208        self.batch_size
209            .unwrap_or_else(|| self.write_mode.max_batch_size())
210    }
211
212    pub fn validate(&self) -> Result<(), String> {
213        if self.table.trim().is_empty() {
214            return Err("table cannot be empty".to_string());
215        }
216        if self.table.len() < 3 || self.table.len() > 255 {
217            return Err(format!(
218                "table name '{}' is {} character(s); DynamoDB requires 3–255 characters",
219                self.table,
220                self.table.len()
221            ));
222        }
223        if !self
224            .table
225            .chars()
226            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.')
227        {
228            return Err(format!(
229                "table name '{}' contains invalid characters; DynamoDB requires [a-zA-Z0-9_.-]",
230                self.table
231            ));
232        }
233        if self.region.trim().is_empty() {
234            return Err("region cannot be empty".to_string());
235        }
236        if let Some(batch_size) = self.batch_size {
237            let max_batch_size = self.write_mode.max_batch_size();
238            if batch_size == 0 || batch_size > max_batch_size {
239                return Err(format!(
240                    "batch_size must be between 1 and {max_batch_size} for {:?} write mode",
241                    self.write_mode
242                ));
243            }
244        }
245        if self.threads == 0 {
246            return Err("threads must be at least 1".to_string());
247        }
248        if self.max_buffer_size.is_zero() {
249            return Err("max_buffer_size must be greater than 0".to_string());
250        }
251        if self.max_concurrent_requests == 0 {
252            return Err("max_concurrent_requests must be greater than 0".to_string());
253        }
254        match (&self.aws_access_key_id, &self.aws_secret_access_key) {
255            (Some(_), Some(_)) | (None, None) => {}
256            _ => {
257                return Err(
258                    "aws_access_key_id and aws_secret_access_key must be specified together"
259                        .to_string(),
260                );
261            }
262        }
263        for (field, expression) in [
264            ("put_condition_expression", &self.put_condition_expression),
265            (
266                "delete_condition_expression",
267                &self.delete_condition_expression,
268            ),
269        ] {
270            if let Some(expression) = expression {
271                if expression.trim().is_empty() {
272                    return Err(format!("{field} cannot be empty"));
273                }
274                if self.write_mode != DynamoDBWriteMode::Transactional {
275                    return Err(format!(
276                        "{field} requires the 'transactional' write mode; conditional writes \
277                         are not supported for 'batch' writes"
278                    ));
279                }
280            }
281        }
282        Ok(())
283    }
284}
285
286impl DynamoDBWriteMode {
287    pub fn max_batch_size(self) -> usize {
288        match self {
289            Self::Batch => 25,
290            Self::Transactional => 100,
291        }
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    fn config(write_mode: DynamoDBWriteMode, batch_size: Option<usize>) -> DynamoDBWriterConfig {
300        DynamoDBWriterConfig {
301            table: "test_table".to_string(),
302            region: "us-east-1".to_string(),
303            endpoint_url: None,
304            aws_access_key_id: None,
305            aws_secret_access_key: None,
306            batch_size,
307            write_mode,
308            max_buffer_size: ConfigSize::from_mib(1),
309            max_concurrent_requests: 16,
310            threads: 1,
311            max_retries: Some(10u8),
312            put_condition_expression: None,
313            delete_condition_expression: None,
314        }
315    }
316
317    #[test]
318    fn default_batch_size_is_mode_specific() {
319        assert_eq!(
320            config(DynamoDBWriteMode::Batch, None).effective_batch_size(),
321            25
322        );
323        assert_eq!(
324            config(DynamoDBWriteMode::Transactional, None).effective_batch_size(),
325            100
326        );
327    }
328
329    #[test]
330    fn explicit_batch_size_is_validated_against_mode_limit() {
331        assert!(
332            config(DynamoDBWriteMode::Batch, Some(25))
333                .validate()
334                .is_ok()
335        );
336        assert!(
337            config(DynamoDBWriteMode::Batch, Some(26))
338                .validate()
339                .is_err()
340        );
341        assert!(
342            config(DynamoDBWriteMode::Transactional, Some(100))
343                .validate()
344                .is_ok()
345        );
346        assert!(
347            config(DynamoDBWriteMode::Transactional, Some(101))
348                .validate()
349                .is_err()
350        );
351    }
352
353    #[test]
354    fn table_name_validation() {
355        let base = config(DynamoDBWriteMode::Batch, None);
356
357        // too short
358        assert!(
359            DynamoDBWriterConfig {
360                table: "ab".to_string(),
361                ..base.clone()
362            }
363            .validate()
364            .is_err()
365        );
366        // minimum length
367        assert!(
368            DynamoDBWriterConfig {
369                table: "abc".to_string(),
370                ..base.clone()
371            }
372            .validate()
373            .is_ok()
374        );
375        // too long
376        assert!(
377            DynamoDBWriterConfig {
378                table: "a".repeat(256),
379                ..base.clone()
380            }
381            .validate()
382            .is_err()
383        );
384        // maximum length
385        assert!(
386            DynamoDBWriterConfig {
387                table: "a".repeat(255),
388                ..base.clone()
389            }
390            .validate()
391            .is_ok()
392        );
393        // invalid characters
394        assert!(
395            DynamoDBWriterConfig {
396                table: "my/table".to_string(),
397                ..base.clone()
398            }
399            .validate()
400            .is_err()
401        );
402        assert!(
403            DynamoDBWriterConfig {
404                table: "my table".to_string(),
405                ..base.clone()
406            }
407            .validate()
408            .is_err()
409        );
410        // valid characters
411        assert!(
412            DynamoDBWriterConfig {
413                table: "my.table-name_1".to_string(),
414                ..base.clone()
415            }
416            .validate()
417            .is_ok()
418        );
419    }
420
421    #[test]
422    fn condition_requires_transactional_write_mode() {
423        // A put condition in batch mode is rejected.
424        let batch = DynamoDBWriterConfig {
425            put_condition_expression: Some("attribute_not_exists(id)".to_string()),
426            ..config(DynamoDBWriteMode::Batch, None)
427        };
428        assert!(batch.validate().is_err());
429
430        // The same condition is accepted in transactional mode.
431        let transactional = DynamoDBWriterConfig {
432            put_condition_expression: Some("attribute_not_exists(id)".to_string()),
433            ..config(DynamoDBWriteMode::Transactional, None)
434        };
435        assert!(transactional.validate().is_ok());
436
437        // A delete condition in batch mode is rejected as well.
438        let batch_delete = DynamoDBWriterConfig {
439            delete_condition_expression: Some("attribute_exists(id)".to_string()),
440            ..config(DynamoDBWriteMode::Batch, None)
441        };
442        assert!(batch_delete.validate().is_err());
443    }
444
445    #[test]
446    fn blank_condition_is_rejected() {
447        let cfg = DynamoDBWriterConfig {
448            put_condition_expression: Some("   ".to_string()),
449            ..config(DynamoDBWriteMode::Transactional, None)
450        };
451        assert!(cfg.validate().is_err());
452    }
453
454    #[test]
455    fn null_max_retries_deserializes_as_unbounded() {
456        let json = r#"{"table":"t","region":"us-east-1","max_retries":null}"#;
457        let cfg: DynamoDBWriterConfig = serde_json::from_str(json).unwrap();
458        assert_eq!(cfg.max_retries, None);
459    }
460
461    #[test]
462    fn omitted_max_retries_deserializes_as_default() {
463        let json = r#"{"table":"t","region":"us-east-1"}"#;
464        let cfg: DynamoDBWriterConfig = serde_json::from_str(json).unwrap();
465        assert_eq!(cfg.max_retries, Some(10u8));
466    }
467}