diff --git a/crates/core/src/error/mod.rs b/crates/core/src/error/mod.rs index 94b81c466..f135a99e9 100755 --- a/crates/core/src/error/mod.rs +++ b/crates/core/src/error/mod.rs @@ -9,6 +9,50 @@ pub use messages::{ use crate::types::{CancellationReason, Item}; +/// One entry of the reasons list the service returns on a throttle error. +/// Measured against Amazon DynamoDB on 2026-10-20 (435 raw throttle bodies, +/// one Region) and 2026-10-24 (9,622, two Regions): every reasons list that +/// was present carried exactly one entry of this shape. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct ThrottlingReason { + /// `ResourceType + OperationType + LimitType`, for example + /// `TableWriteProvisionedThroughputExceeded` or + /// `IndexReadProvisionedThroughputExceeded`. + pub reason: String, + /// The table or index ARN, the string `DescribeTable` returns as + /// `TableArn` or `IndexArn`. + pub resource: String, +} + +/// The `ProvisionedThroughputExceededException` message the service sends +/// when a table's own provisioned capacity is exceeded, on every read and +/// write operation, and on a hot key or an index read of a provisioned +/// table. Measured 2026-10-20 (424 of 424: 423 writes on the table's own +/// capacity and one hot-key write) and 2026-10-24 (1,538 read throttles on +/// the table's own capacity, 648 index reads and 162 writes in a second +/// Region, all carrying this text; the 104 index-write bodies of that run +/// carry a different message naming global secondary indexes, which the +/// server does not model). Trailing period. +pub const PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE: &str = "The level of configured provisioned throughput for the table was exceeded. Consider increasing your provisioning level with the UpdateTable API."; + +/// The `ThrottlingException` message the service sends on an on-demand table +/// whose partition is hot. Measured 2026-10-20 (11 of 11) and 2026-10-24 +/// (7,070 of 7,070, two Regions). No trailing period. +pub const THROTTLING_EXCEPTION_MESSAGE: &str = "Throughput exceeds the current capacity of your table or index. DynamoDB is automatically scaling your table or index so please try again shortly. If exceptions persist, check if you have a hot key: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-partition-key-design.html"; + +/// The `ThrottlingException` message the service sends when an on-demand +/// table reaches the `OnDemandThroughput` caps set on it. Measured +/// 2026-10-24 (100 of 100: 52 `Query` reads, 48 `BatchWriteItem` writes). No +/// trailing period. +pub const MAX_ON_DEMAND_THROUGHPUT_MESSAGE: &str = + "Throughput exceeds the maximum OnDemandThroughput configured on table or index"; + +/// `RequestLimitExceeded` wording. The API Reference (PutItem Errors, read +/// 2026-10-20) describes the error as throughput exceeding the account's +/// quota and points at Support for an increase; the wire `message` field has +/// not been measured, so this text is the documented description. +pub const REQUEST_LIMIT_EXCEEDED_MESSAGE: &str = "Throughput exceeds the current throughput quota for your account. Please contact Amazon Web Services Support to request a quota increase."; + /// All Virtual `DynamoDB` error types with HTTP status codes. /// /// REQ-ERR-001 through REQ-ERR-004: error JSON format, status codes, and SDK retry behavior. @@ -121,15 +165,42 @@ pub enum DynamoDbError { /// SP-ERR-002: Concurrent modification of the same item in a transaction. #[error("{0}")] TransactionConflictException(String), - /// SP-ERR-002: Throughput exceeded. - #[error("{0}")] - ProvisionedThroughputExceededException(String), - /// SP-ERR-002: General throttling. - #[error("{0}")] - ThrottlingException(String), - /// SP-ERR-002: Per-account RPS cap. - #[error("{0}")] - RequestLimitExceeded(String), + /// SP-ERR-002: Throughput exceeded. HTTP 400. The reasons list is + /// rendered as `ThrottlingReasons` (capital T, measured 2026-10-20 and + /// 2026-10-24) and omitted when empty. + #[error("{message}")] + ProvisionedThroughputExceededException { + /// Human-readable message; the service's text for a table's own + /// capacity is [`PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE`]. + message: String, + /// One entry per throttled resource. + reasons: Vec, + }, + /// SP-ERR-002: General throttling. HTTP 400. The `__type` namespace is + /// `com.amazon.coral.availability#` and the reasons list is rendered as + /// `throttlingReasons` (lower t), both measured 2026-10-20 and + /// 2026-10-24. The list is omitted when empty, which is what the service + /// sends for a hot-key read on an on-demand table (5,615 of 5,615). + #[error("{message}")] + ThrottlingException { + /// Human-readable message; [`THROTTLING_EXCEPTION_MESSAGE`] for a hot + /// key, [`MAX_ON_DEMAND_THROUGHPUT_MESSAGE`] at the table's caps. + message: String, + /// One entry per throttled resource. + reasons: Vec, + }, + /// SP-ERR-002: Per-account throughput quota. HTTP 400. The API Reference + /// documents a `ThrottlingReasons` member on this error (PutItem Errors, + /// read 2026-10-20); rendered with that casing and omitted when empty. + /// Not measured: the probes did not reach an account quota. + #[error("{message}")] + RequestLimitExceeded { + /// Human-readable message; [`REQUEST_LIMIT_EXCEEDED_MESSAGE`] is the + /// documented wording. + message: String, + /// One entry per throttled resource. + reasons: Vec, + }, /// SP-ERR-002 / SP-WIRE-007: Request body exceeds 16 MB. HTTP 413. #[error("{0}")] RequestEntityTooLargeException(String), @@ -177,9 +248,9 @@ impl DynamoDbError { | Self::ContinuousBackupsUnavailableException(_) | Self::PointInTimeRecoveryUnavailableException(_) | Self::TransactionConflictException(_) - | Self::ProvisionedThroughputExceededException(_) - | Self::ThrottlingException(_) - | Self::RequestLimitExceeded(_) + | Self::ProvisionedThroughputExceededException { .. } + | Self::ThrottlingException { .. } + | Self::RequestLimitExceeded { .. } | Self::MalformedHttpRequestException(_) | Self::TransactionInProgressException(_) | Self::ItemCollectionSizeLimitExceededException(_) @@ -235,11 +306,11 @@ impl DynamoDbError { } Self::ServiceUnavailable(_) => "ServiceUnavailable", Self::TransactionConflictException(_) => "TransactionConflictException", - Self::ProvisionedThroughputExceededException(_) => { + Self::ProvisionedThroughputExceededException { .. } => { "ProvisionedThroughputExceededException" } - Self::ThrottlingException(_) => "ThrottlingException", - Self::RequestLimitExceeded(_) => "RequestLimitExceeded", + Self::ThrottlingException { .. } => "ThrottlingException", + Self::RequestLimitExceeded { .. } => "RequestLimitExceeded", Self::RequestEntityTooLargeException(_) => "RequestEntityTooLargeException", Self::MalformedHttpRequestException(_) => "MalformedHttpRequestException", Self::TransactionInProgressException(_) => "TransactionInProgressException", @@ -261,9 +332,12 @@ impl DynamoDbError { /// (`SerializationException`, `UnknownOperationException`, /// `MissingAuthenticationToken`, `IncompleteSignature`, /// `InvalidSignatureException`) + /// - `ThrottlingException` → `com.amazon.coral.availability#` (measured + /// 2026-10-20, 11 of 11, and 2026-10-24, 7,170 of 7,170 on-demand + /// throttles) /// - All other `DynamoDB` errors → `com.amazonaws.dynamodb.v20120810#` /// - /// Verified against real `DynamoDB` 2026-05-04. + /// Verified against the service 2026-05-04 and 2026-10-24. #[must_use] pub fn full_error_type(&self) -> String { let prefix = match self { @@ -273,6 +347,7 @@ impl DynamoDbError { | Self::MissingAuthenticationToken(_) | Self::IncompleteSignature(_) | Self::InvalidSignatureException(_) => "com.amazon.coral.service#", + Self::ThrottlingException { .. } => "com.amazon.coral.availability#", _ => "com.amazonaws.dynamodb.v20120810#", }; format!("{prefix}{}", self.error_type()) @@ -307,9 +382,9 @@ impl DynamoDbError { | Self::PointInTimeRecoveryUnavailableException(m) | Self::ServiceUnavailable(m) | Self::TransactionConflictException(m) - | Self::ProvisionedThroughputExceededException(m) - | Self::ThrottlingException(m) - | Self::RequestLimitExceeded(m) + | Self::ProvisionedThroughputExceededException { message: m, .. } + | Self::ThrottlingException { message: m, .. } + | Self::RequestLimitExceeded { message: m, .. } | Self::RequestEntityTooLargeException(m) | Self::MalformedHttpRequestException(m) | Self::TransactionInProgressException(m) @@ -341,6 +416,58 @@ impl DynamoDbError { _ => None, } } + + /// A `ProvisionedThroughputExceededException` carrying `reasons`. + #[must_use] + pub fn provisioned_throughput_exceeded( + message: impl Into, + reasons: Vec, + ) -> Self { + Self::ProvisionedThroughputExceededException { + message: message.into(), + reasons, + } + } + + /// A `ThrottlingException` carrying `reasons`. + #[must_use] + pub fn throttling(message: impl Into, reasons: Vec) -> Self { + Self::ThrottlingException { + message: message.into(), + reasons, + } + } + + /// A `RequestLimitExceeded` carrying `reasons`. + #[must_use] + pub fn request_limit_exceeded( + message: impl Into, + reasons: Vec, + ) -> Self { + Self::RequestLimitExceeded { + message: message.into(), + reasons, + } + } + + /// For the three throttle errors (`ProvisionedThroughputExceededException`, + /// `ThrottlingException`, `RequestLimitExceeded`), the per-resource + /// reasons, possibly empty; `None` for every other variant. + #[must_use] + pub fn throttling_reasons(&self) -> Option<&[ThrottlingReason]> { + match self { + Self::ProvisionedThroughputExceededException { reasons, .. } + | Self::ThrottlingException { reasons, .. } + | Self::RequestLimitExceeded { reasons, .. } => Some(reasons), + _ => None, + } + } + + /// Whether this error is one of the three throttle errors. + #[must_use] + pub fn is_throttle(&self) -> bool { + self.throttling_reasons().is_some() + } } /// Fallback body for when serializing an already-built response itself fails. @@ -360,9 +487,10 @@ pub const SERIALIZATION_FAILURE_BODY: &[u8] = /// its namespace prefix (REQ-ERR-001), an optional message under the key /// `message_key` picks (REQ-ERR-002), omitted when empty /// (REQ-ERR-003 — real DynamoDB omits it for `UnknownOperationException` and -/// other messageless errors), and the `CancellationReasons` /`Item` members +/// other messageless errors), the `CancellationReasons` /`Item` members /// that `TransactionCanceledException` and `ConditionalCheckFailedException` -/// carry. This is only the body; the HTTP status line and headers belong to a +/// carry, and the reasons list of the three throttle errors. This is only the +/// body; the HTTP status line and headers belong to a /// transport and stay with the caller that has one. Error responses are part of /// the observable contract, so every entry point builds this body the same way. #[doc(hidden)] @@ -376,6 +504,21 @@ pub fn error_document(error: &DynamoDbError) -> serde_json::Value { if let Some(reasons) = error.cancellation_reasons() { body["CancellationReasons"] = serde_json::to_value(reasons).unwrap_or_default(); } + // Throttle errors carry one reason per throttled resource. The field name + // differs by error class: `ThrottlingReasons` on + // ProvisionedThroughputExceededException and RequestLimitExceeded, + // `throttlingReasons` on ThrottlingException (measured against the service + // 2026-10-20 and 2026-10-24). Omitted when the list is empty, which is what + // the service sends for a hot-key read on an on-demand table. + if let Some(reasons) = error.throttling_reasons() + && !reasons.is_empty() + { + let field = match error { + DynamoDbError::ThrottlingException { .. } => "throttlingReasons", + _ => "ThrottlingReasons", + }; + body[field] = serde_json::to_value(reasons).unwrap_or_default(); + } if let Some(item) = error.condition_check_item() { body["Item"] = serde_json::to_value(item).unwrap_or_default(); } @@ -458,14 +601,17 @@ mod tests { 400, ), ( - DynamoDbError::ProvisionedThroughputExceededException(String::new()), + DynamoDbError::provisioned_throughput_exceeded(String::new(), vec![]), 400, ), ( DynamoDbError::RequestEntityTooLargeException(String::new()), 413, ), - (DynamoDbError::RequestLimitExceeded(String::new()), 400), + ( + DynamoDbError::request_limit_exceeded(String::new(), vec![]), + 400, + ), (DynamoDbError::RequestTimeoutException(String::new()), 408), (DynamoDbError::ResourceInUseException(String::new()), 400), ( @@ -477,7 +623,7 @@ mod tests { (DynamoDbError::BackupInUseException(String::new()), 400), (DynamoDbError::SerializationException(String::new()), 400), (DynamoDbError::ServiceUnavailable(String::new()), 503), - (DynamoDbError::ThrottlingException(String::new()), 400), + (DynamoDbError::throttling(String::new(), vec![]), 400), ( DynamoDbError::TransactionCanceledException { message: String::new(), @@ -599,3 +745,6 @@ mod tests { ); } } + +#[cfg(test)] +mod throttle_tests; diff --git a/crates/core/src/error/throttle_tests.rs b/crates/core/src/error/throttle_tests.rs new file mode 100644 index 000000000..cd59e5ef4 --- /dev/null +++ b/crates/core/src/error/throttle_tests.rs @@ -0,0 +1,169 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! The three throttle error classes: status, type name, namespace, reasons, +//! and the error document of each. + +use super::*; + +const ARN: &str = "arn:aws:dynamodb:us-east-1:123456789012:table/T"; + +fn reason(code: &str) -> ThrottlingReason { + ThrottlingReason { + reason: code.to_owned(), + resource: ARN.to_owned(), + } +} + +/// The three throttle classes keep their status and type name, carry their +/// reasons through the accessor, and answer `is_throttle`. +#[test] +fn throttle_errors_carry_reasons_and_keep_their_class() { + let cases = [ + ( + DynamoDbError::provisioned_throughput_exceeded( + PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + vec![reason("TableWriteProvisionedThroughputExceeded")], + ), + "ProvisionedThroughputExceededException", + PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + ), + ( + DynamoDbError::throttling( + THROTTLING_EXCEPTION_MESSAGE, + vec![reason("TableWriteKeyRangeThroughputExceeded")], + ), + "ThrottlingException", + THROTTLING_EXCEPTION_MESSAGE, + ), + ( + DynamoDbError::request_limit_exceeded( + REQUEST_LIMIT_EXCEEDED_MESSAGE, + vec![reason("TableWriteAccountLimitExceeded")], + ), + "RequestLimitExceeded", + REQUEST_LIMIT_EXCEEDED_MESSAGE, + ), + ]; + for (err, type_name, message) in cases { + assert_eq!(err.status_code(), 400, "{type_name}"); + assert_eq!(err.error_type(), type_name); + assert_eq!(err.message(), message); + assert_eq!(err.to_string(), message); + assert!(err.is_throttle(), "{type_name}"); + let reasons = err.throttling_reasons().expect("reasons"); + assert_eq!(reasons.len(), 1, "{type_name}"); + assert_eq!(reasons[0].resource, ARN); + } +} + +/// An empty reasons list is still `Some` (the class is a throttle); every +/// other variant answers `None` and is not a throttle. +#[test] +fn non_throttle_errors_have_no_reasons() { + assert_eq!( + DynamoDbError::throttling("m", vec![]).throttling_reasons(), + Some(&[][..]) + ); + for err in [ + DynamoDbError::ValidationException("v".to_owned()), + DynamoDbError::InternalServerError("i".to_owned()), + DynamoDbError::ServiceUnavailable("s".to_owned()), + DynamoDbError::TransactionConflictException("c".to_owned()), + ] { + assert!(err.throttling_reasons().is_none(), "{err:?}"); + assert!(!err.is_throttle(), "{err:?}"); + } +} + +/// The reason entry serializes with the two lower-case field names the +/// service uses, in that order. +#[test] +fn throttling_reason_serializes_with_the_measured_field_names() { + let json = serde_json::to_string(&reason("TableReadProvisionedThroughputExceeded")) + .expect("serialize"); + assert_eq!( + json, + r#"{"reason":"TableReadProvisionedThroughputExceeded","resource":"arn:aws:dynamodb:us-east-1:123456789012:table/T"}"# + ); +} + +/// The error document of each throttle class: the namespace, the reasons +/// field and its casing (`ThrottlingReasons` on the provisioned class and +/// `RequestLimitExceeded`, `throttlingReasons` on `ThrottlingException`), the +/// list omitted when empty, and the message. The three measured messages are +/// written out here, so a change to a message constant fails this test. +#[test] +fn throttle_error_documents_match_the_service() { + let one = |code: &str| vec![reason(code)]; + let listed = |code: &str| serde_json::json!([{"reason": code, "resource": ARN}]); + let provisioned = "com.amazonaws.dynamodb.v20120810#ProvisionedThroughputExceededException"; + let throttling = "com.amazon.coral.availability#ThrottlingException"; + let request_limit = "com.amazonaws.dynamodb.v20120810#RequestLimitExceeded"; + let measured_provisioned = "The level of configured provisioned throughput for the table was exceeded. Consider increasing your provisioning level with the UpdateTable API."; + let measured_hot_key = "Throughput exceeds the current capacity of your table or index. DynamoDB is automatically scaling your table or index so please try again shortly. If exceptions persist, check if you have a hot key: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-partition-key-design.html"; + let measured_caps = + "Throughput exceeds the maximum OnDemandThroughput configured on table or index"; + let cases = [ + ( + DynamoDbError::provisioned_throughput_exceeded( + PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + one("TableWriteProvisionedThroughputExceeded"), + ), + serde_json::json!({ + "__type": provisioned, + "message": measured_provisioned, + "ThrottlingReasons": listed("TableWriteProvisionedThroughputExceeded"), + }), + ), + ( + DynamoDbError::throttling( + THROTTLING_EXCEPTION_MESSAGE, + one("TableWriteKeyRangeThroughputExceeded"), + ), + serde_json::json!({ + "__type": throttling, + "message": measured_hot_key, + "throttlingReasons": listed("TableWriteKeyRangeThroughputExceeded"), + }), + ), + ( + DynamoDbError::throttling( + MAX_ON_DEMAND_THROUGHPUT_MESSAGE, + one("TableReadMaxOnDemandThroughputExceeded"), + ), + serde_json::json!({ + "__type": throttling, + "message": measured_caps, + "throttlingReasons": listed("TableReadMaxOnDemandThroughputExceeded"), + }), + ), + ( + DynamoDbError::request_limit_exceeded( + "Too many requests", + one("TableWriteAccountLimitExceeded"), + ), + serde_json::json!({ + "__type": request_limit, + "message": "Too many requests", + "ThrottlingReasons": listed("TableWriteAccountLimitExceeded"), + }), + ), + // A hot-key read on an on-demand table: no reasons list under either + // spelling, which is what the service sends (5,615 of 5,615). + ( + DynamoDbError::throttling(THROTTLING_EXCEPTION_MESSAGE, vec![]), + serde_json::json!({"__type": throttling, "message": measured_hot_key}), + ), + ( + DynamoDbError::provisioned_throughput_exceeded("m", vec![]), + serde_json::json!({"__type": provisioned, "message": "m"}), + ), + ( + DynamoDbError::request_limit_exceeded("m", vec![]), + serde_json::json!({"__type": request_limit, "message": "m"}), + ), + ]; + for (error, expected) in cases { + assert_eq!(error_document(&error), expected, "{error:?}"); + } +} diff --git a/crates/core/src/throttle.rs b/crates/core/src/throttle.rs index c7167c583..61538493b 100755 --- a/crates/core/src/throttle.rs +++ b/crates/core/src/throttle.rs @@ -94,9 +94,14 @@ impl TokenBucket { let old_max = self.max_tokens; self.max_tokens = new_rate * BURST_SECONDS; self.refill_rate = new_rate; - // Scale current tokens proportionally. if old_max > 0.0 { - self.tokens = (self.tokens / old_max * self.max_tokens).min(self.max_tokens); + // A positive balance keeps its share of the burst window. A debt + // (the balance below zero that an operation larger than the + // balance leaves) keeps its token count and is repaid at the new + // rate. + if self.tokens > 0.0 { + self.tokens = (self.tokens / old_max * self.max_tokens).min(self.max_tokens); + } } else { self.tokens = self.max_tokens; } @@ -112,6 +117,12 @@ pub struct TableThroughput { pub wcu: f64, /// Whether this is an on-demand table. pub on_demand: bool, + /// Whether the read rate is an `OnDemandThroughput` cap set on the table + /// rather than the default on-demand ceiling. The service names the limit + /// differently on a throttle (`MaxOnDemandThroughputExceeded`). + pub read_capped: bool, + /// Whether the write rate is an `OnDemandThroughput` cap. + pub write_capped: bool, } impl TableThroughput { @@ -123,6 +134,8 @@ impl TableThroughput { rcu: rcu as f64, wcu: wcu as f64, on_demand: false, + read_capped: false, + write_capped: false, } } @@ -133,6 +146,34 @@ impl TableThroughput { rcu: ON_DEMAND_DEFAULT_RCU, wcu: ON_DEMAND_DEFAULT_WCU, on_demand: true, + read_capped: false, + write_capped: false, + } + } + + /// Create throughput config for an on-demand table whose + /// `OnDemandThroughput` caps are set. A cap that is absent or not positive + /// (the service uses `-1` to remove one) keeps the default ceiling for + /// that direction, and only the capped direction reports the caps limit + /// on a throttle. + #[must_use] + #[allow(clippy::cast_precision_loss)] // request-unit caps are small enough for f64 + pub fn on_demand_capped( + max_read_request_units: Option, + max_write_request_units: Option, + ) -> Self { + let cap = |units: Option, default: f64| match units { + Some(n) if n > 0 => (n as f64, true), + _ => (default, false), + }; + let (rcu, read_capped) = cap(max_read_request_units, ON_DEMAND_DEFAULT_RCU); + let (wcu, write_capped) = cap(max_write_request_units, ON_DEMAND_DEFAULT_WCU); + Self { + rcu, + wcu, + on_demand: true, + read_capped, + write_capped, } } } @@ -156,6 +197,12 @@ struct PartitionKey { struct TableBuckets { read: TokenBucket, write: TokenBucket, + /// Billing mode the table was registered with; carried into the + /// [`ThrottleCause`] so the server can name the limit the service would. + on_demand: bool, + /// Whether each rate is an `OnDemandThroughput` cap. + read_capped: bool, + write_capped: bool, } /// Account-level aggregate bucket pair. @@ -170,9 +217,43 @@ pub enum ThrottleResult { /// Request may proceed. Allowed, /// Request is throttled on reads. - ThrottledRead, + ThrottledRead(ThrottleCause), /// Request is throttled on writes. - ThrottledWrite, + ThrottledWrite(ThrottleCause), +} + +impl ThrottleResult { + /// The bucket that refused, or `None` when the request was allowed. + #[must_use] + pub fn cause(&self) -> Option { + match self { + Self::Allowed => None, + Self::ThrottledRead(c) | Self::ThrottledWrite(c) => Some(*c), + } + } +} + +/// Which bucket refused a request. The service names the throttled resource +/// and the limit on a throttle error (`ThrottlingReasons`); the server maps +/// this cause and the table's billing mode onto that vocabulary. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ThrottleCause { + /// The table's own bucket: its provisioned capacity, the default ceiling + /// of an on-demand table, or an `OnDemandThroughput` cap set on one. + Table { + /// Whether the table is billed on demand. + on_demand: bool, + /// Whether the rate of the bucket that refused (read or write) is an + /// `OnDemandThroughput` cap. + capped: bool, + }, + /// The per-partition-key bucket (a hot key). + Partition { + /// Whether the table is billed on demand. + on_demand: bool, + }, + /// The per-account aggregate bucket. + Account, } /// Thread-safe throttle manager holding all token buckets. @@ -230,12 +311,18 @@ impl ThrottleManager { if let Some(existing) = tables.get_mut(&key) { existing.read.update_rate(throughput.rcu); existing.write.update_rate(throughput.wcu); + existing.on_demand = throughput.on_demand; + existing.read_capped = throughput.read_capped; + existing.write_capped = throughput.write_capped; } else { tables.insert( key, TableBuckets { read: TokenBucket::new(throughput.rcu), write: TokenBucket::new(throughput.wcu), + on_demand: throughput.on_demand, + read_capped: throughput.read_capped, + write_capped: throughput.write_capped, }, ); } @@ -296,6 +383,7 @@ impl ThrottleManager { } let now = Instant::now(); + let mut on_demand = false; // Check per-table bucket. if let Ok(mut tables) = self.tables.write() { @@ -304,11 +392,18 @@ impl ThrottleManager { table_name: table_name.to_owned(), }; if let Some(buckets) = tables.get_mut(&key) { + on_demand = buckets.on_demand; if is_read && !buckets.read.has_capacity(now) { - return ThrottleResult::ThrottledRead; + return ThrottleResult::ThrottledRead(ThrottleCause::Table { + on_demand, + capped: buckets.read_capped, + }); } if is_write && !buckets.write.has_capacity(now) { - return ThrottleResult::ThrottledWrite; + return ThrottleResult::ThrottledWrite(ThrottleCause::Table { + on_demand, + capped: buckets.write_capped, + }); } } } @@ -325,12 +420,16 @@ impl ThrottleManager { let buckets = partitions.entry(pk).or_insert_with(|| TableBuckets { read: TokenBucket::new(PARTITION_RCU_LIMIT), write: TokenBucket::new(PARTITION_WCU_LIMIT), + on_demand, + read_capped: false, + write_capped: false, }); + let cause = ThrottleCause::Partition { on_demand }; if is_read && !buckets.read.has_capacity(now) { - return ThrottleResult::ThrottledRead; + return ThrottleResult::ThrottledRead(cause); } if is_write && !buckets.write.has_capacity(now) { - return ThrottleResult::ThrottledWrite; + return ThrottleResult::ThrottledWrite(cause); } } @@ -343,10 +442,10 @@ impl ThrottleManager { write: TokenBucket::new(self.account_wcu_limit), }); if is_read && !acct.read.has_capacity(now) { - return ThrottleResult::ThrottledRead; + return ThrottleResult::ThrottledRead(ThrottleCause::Account); } if is_write && !acct.write.has_capacity(now) { - return ThrottleResult::ThrottledWrite; + return ThrottleResult::ThrottledWrite(ThrottleCause::Account); } } @@ -402,6 +501,11 @@ impl ThrottleManager { let buckets = partitions.entry(pk).or_insert_with(|| TableBuckets { read: TokenBucket::new(PARTITION_RCU_LIMIT), write: TokenBucket::new(PARTITION_WCU_LIMIT), + // Partition buckets take their limits from the constants; the + // billing mode is read from the table's bucket at check time. + on_demand: false, + read_capped: false, + write_capped: false, }); if read_units > 0.0 { buckets.read.consume(read_units, now); @@ -495,7 +599,10 @@ mod tests { mgr.consume("acct", "tbl", 2.0, 0.0); assert_eq!( mgr.check_capacity("acct", "tbl", true, false), - ThrottleResult::ThrottledRead + ThrottleResult::ThrottledRead(ThrottleCause::Table { + on_demand: false, + capped: false, + }) ); } @@ -506,7 +613,10 @@ mod tests { mgr.consume("acct", "tbl", 0.0, 2.0); assert_eq!( mgr.check_capacity("acct", "tbl", false, true), - ThrottleResult::ThrottledWrite + ThrottleResult::ThrottledWrite(ThrottleCause::Table { + on_demand: false, + capped: false, + }) ); } @@ -535,7 +645,7 @@ mod tests { mgr.consume("acct", "tbl", 2.0, 0.0); assert_eq!( mgr.check_capacity("acct", "tbl", true, false), - ThrottleResult::ThrottledRead + ThrottleResult::ThrottledRead(ThrottleCause::Account) ); } @@ -559,3 +669,6 @@ mod tests { assert_eq!(bucket.refill_rate, 200.0); } } + +#[cfg(test)] +mod cause_tests; diff --git a/crates/core/src/throttle/cause_tests.rs b/crates/core/src/throttle/cause_tests.rs new file mode 100644 index 000000000..8d5d843ae --- /dev/null +++ b/crates/core/src/throttle/cause_tests.rs @@ -0,0 +1,178 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! The cause a refusal carries and the OnDemandThroughput caps sizing. + +use super::*; + +/// A hot partition key names the partition bucket and carries the table's +/// billing mode, read from the table's own bucket. +#[test] +fn partition_throttle_carries_the_billing_mode() { + for (throughput, on_demand) in [ + (TableThroughput::provisioned(100_000, 100_000), false), + (TableThroughput::on_demand(), true), + ] { + let mgr = ThrottleManager::new(1_000_000, 1_000_000, true); + // Drain the partition bucket before the table is registered, so the + // table bucket starts full. + mgr.consume_with_partition("acct", "tbl", 0.0, 1.0e9, Some("k")); + mgr.register_table("acct", "tbl", throughput); + assert_eq!( + mgr.check_capacity_with_partition("acct", "tbl", false, true, Some("k")), + ThrottleResult::ThrottledWrite(ThrottleCause::Partition { on_demand }), + "on_demand={on_demand}" + ); + } +} + +/// An on-demand table with `OnDemandThroughput` caps is sized by the caps +/// and refuses with the capped cause; an absent or non-positive cap keeps +/// the default ceiling for its direction. +#[test] +fn on_demand_caps_size_the_table_bucket() { + let capped = TableThroughput::on_demand_capped(Some(1), Some(1)); + assert!(capped.on_demand && capped.read_capped && capped.write_capped); + assert_eq!((capped.rcu, capped.wcu), (1.0, 1.0)); + + let half = TableThroughput::on_demand_capped(None, Some(5)); + assert!(!half.read_capped && half.write_capped); + assert_eq!((half.rcu, half.wcu), (ON_DEMAND_DEFAULT_RCU, 5.0)); + + let removed = TableThroughput::on_demand_capped(Some(-1), Some(-1)); + assert!(!removed.read_capped && !removed.write_capped); + assert_eq!( + (removed.rcu, removed.wcu), + (ON_DEMAND_DEFAULT_RCU, ON_DEMAND_DEFAULT_WCU) + ); + + let mgr = ThrottleManager::new(1_000_000, 1_000_000, true); + mgr.register_table("acct", "tbl", capped); + mgr.consume("acct", "tbl", 0.0, 1.0e9); + assert_eq!( + mgr.check_capacity("acct", "tbl", false, true), + ThrottleResult::ThrottledWrite(ThrottleCause::Table { + on_demand: true, + capped: true, + }) + ); + assert_eq!( + mgr.check_capacity("acct", "tbl", false, true).cause(), + Some(ThrottleCause::Table { + on_demand: true, + capped: true, + }) + ); + assert_eq!(ThrottleResult::Allowed.cause(), None); +} + +/// A table capped in one direction reports the caps limit only for a +/// refusal in that direction; the other direction is the default ceiling. +#[test] +fn half_capped_table_reports_the_cap_for_its_direction_only() { + let mgr = ThrottleManager::new(1_000_000, 1_000_000, true); + mgr.register_table( + "acct", + "tbl", + TableThroughput::on_demand_capped(None, Some(1)), + ); + // Drain both buckets: the write cap of 1 and the default read ceiling. + mgr.consume("acct", "tbl", 1.0e9, 1.0e9); + assert_eq!( + mgr.check_capacity("acct", "tbl", false, true), + ThrottleResult::ThrottledWrite(ThrottleCause::Table { + on_demand: true, + capped: true, + }) + ); + assert_eq!( + mgr.check_capacity("acct", "tbl", true, false), + ThrottleResult::ThrottledRead(ThrottleCause::Table { + on_demand: true, + capped: false, + }) + ); +} + +/// Re-registering a table (UpdateTable) moves its billing mode and caps. +#[test] +fn register_table_updates_the_billing_mode() { + let mgr = ThrottleManager::new(1_000_000, 1_000_000, true); + mgr.register_table("acct", "tbl", TableThroughput::provisioned(1, 1)); + mgr.register_table( + "acct", + "tbl", + TableThroughput::on_demand_capped(Some(1), Some(1)), + ); + mgr.consume("acct", "tbl", 1.0e9, 0.0); + assert_eq!( + mgr.check_capacity("acct", "tbl", true, false), + ThrottleResult::ThrottledRead(ThrottleCause::Table { + on_demand: true, + capped: true, + }) + ); +} + +/// Moving from the default on-demand ceilings to a cap keeps the same +/// fraction of the burst window: a fresh default bucket holds one second +/// of 4,000 WCU, which becomes one second of the 1 WRU cap (one token, +/// not the 4,000 the table held a moment before), so a write is allowed +/// and a write of more than one unit leaves the bucket refusing with the +/// capped cause. +#[test] +fn register_table_scales_tokens_to_the_new_cap() { + let mgr = ThrottleManager::new(1_000_000, 1_000_000, true); + mgr.register_table("acct", "tbl", TableThroughput::on_demand()); + mgr.register_table( + "acct", + "tbl", + TableThroughput::on_demand_capped(Some(1), Some(1)), + ); + assert_eq!( + mgr.check_capacity("acct", "tbl", false, true), + ThrottleResult::Allowed + ); + mgr.consume("acct", "tbl", 0.0, 1.5); + assert_eq!( + mgr.check_capacity("acct", "tbl", false, true), + ThrottleResult::ThrottledWrite(ThrottleCause::Table { + on_demand: true, + capped: true, + }) + ); +} + +/// A table in debt has its write cap raised, or removed. One write of 293 +/// units on a cap of 1 leaves a debt of 292 units, which the new rate repays +/// in 29 ms (10,000 units a second) or 73 ms (the 4,000 default), so a write +/// 150 ms after the change is allowed. Scaled with the rates, the debt kept +/// its length of 292 seconds. +#[test] +fn raising_or_removing_a_cap_repays_a_debt_at_the_new_rate() { + for after in [ + TableThroughput::on_demand_capped(None, Some(10_000)), + TableThroughput::on_demand_capped(None, Some(-1)), + ] { + let mgr = ThrottleManager::new(1_000_000, 1_000_000, true); + mgr.register_table( + "acct", + "tbl", + TableThroughput::on_demand_capped(None, Some(1)), + ); + mgr.consume("acct", "tbl", 0.0, 293.0); + assert!( + matches!( + mgr.check_capacity("acct", "tbl", false, true), + ThrottleResult::ThrottledWrite(_) + ), + "{after:?}" + ); + mgr.register_table("acct", "tbl", after); + std::thread::sleep(std::time::Duration::from_millis(150)); + assert_eq!( + mgr.check_capacity("acct", "tbl", false, true), + ThrottleResult::Allowed, + "{after:?}" + ); + } +} diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index 4b49f73d5..4269dab92 100755 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -68,8 +68,9 @@ libc = { workspace = true } [dev-dependencies] extenddb-cache = { path = "../cache", features = ["test-util"] } # The login tests count bcrypt checks with `count_verifications` against an -# in-memory SQLite catalog, and the dev-credential seeding tests run against a -# SQLite catalog file. +# in-memory SQLite catalog, the dev-credential seeding tests run against a +# SQLite catalog file, and the handler tests drive a table through its own +# throttle path on an in-memory SQLite engine. extenddb-storage = { path = "../storage", features = ["test-util"] } extenddb-storage-sqlite = { path = "../storage-sqlite" } sqlx = { workspace = true, features = ["sqlite"] } diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index 3a5091cc0..8f5036cc2 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -22,7 +22,7 @@ use crate::request_helpers::{ use crate::response::{error_response, record_error_metrics, success_response}; use crate::throttle_helpers::{ classify_data_operation, extract_partition_value, table_description_to_throughput, - update_throttle_buckets, + throttle_error, update_throttle_buckets, }; /// Main Virtual `DynamoDB` request handler. @@ -202,8 +202,17 @@ pub(crate) async fn handle_request( let throttle_start = std::time::Instant::now(); let (is_read_op, is_write_op) = classify_data_operation(&operation); let partition_value = extract_partition_value(&input, &operation); + // A name the table name rules refuse (length or pattern), and the ARN of + // a table in another Region, are not throttled: the engine answers them + // as it does with capacity left. The service refuses such a name before + // any throttle (measured 2026-11-25 with GetItem and PutItem on `ab`, an + // empty name, 256 characters and the ARN of a table in another Region). + // The ARN of a table in this account and Region is checked by the name it + // carries, and a throttle refusal names that table. if let Some(ref tn) = table_name && (is_read_op || is_write_op) + && let name = crate::authz_resource::key_lookup_name(tn, &state.region, &ctx.account_id) + && extenddb_core::validation::validate_table_name(&name, &state.limits).is_ok() { if !state.throttle.is_registered(&ctx.account_id, tn) && let Ok(desc) = ctx @@ -229,8 +238,12 @@ pub(crate) async fn handle_request( is_write_op, partition_value.as_deref(), ); - if result != extenddb_core::throttle::ThrottleResult::Allowed { - let metric = if result == extenddb_core::throttle::ThrottleResult::ThrottledRead { + if let Some(cause) = result.cause() { + let throttled_read = matches!( + result, + extenddb_core::throttle::ThrottleResult::ThrottledRead(_) + ); + let metric = if throttled_read { extenddb_core::metrics::MetricName::ReadThrottleEvents } else { extenddb_core::metrics::MetricName::WriteThrottleEvents @@ -251,13 +264,15 @@ pub(crate) async fn handle_request( None, Some(&operation), ); + // The service names the throttled resource and the limit on a + // throttle: one reason with the table ARN, the same string + // DescribeTable returns as TableArn. The error class, the message + // and the limit follow the bucket that refused and the table's + // billing mode. + let table_arn = + extenddb_storage::util::table_arn(&state.region, &ctx.account_id, &name); return error_response( - &DynamoDbError::ProvisionedThroughputExceededException( - "The level of configured provisioned throughput for the table \ - was exceeded. Consider increasing your provisioning level \ - with the UpdateTable API." - .to_owned(), - ), + &throttle_error(cause, throttled_read, &table_arn), &request_id, ); } @@ -423,3 +438,6 @@ pub(crate) async fn handle_request( response } + +#[cfg(test)] +mod throttle_wire_tests; diff --git a/crates/server/src/handler/throttle_wire_tests.rs b/crates/server/src/handler/throttle_wire_tests.rs new file mode 100644 index 000000000..4c90d9a9e --- /dev/null +++ b/crates/server/src/handler/throttle_wire_tests.rs @@ -0,0 +1,479 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! The server's own throttle refusal, driven through `handle_request` against +//! an in-memory engine: the error class, the reasons field and its casing, the +//! reason text and the table ARN the body carries for each bucket that refuses. + +use std::sync::Arc; + +use axum::body::Bytes; +use axum::extract::State; +use axum::http::HeaderMap; +use extenddb_auth::{AuthIdentity, AuthProvider}; +use extenddb_core::error::{ + DynamoDbError, MAX_ON_DEMAND_THROUGHPUT_MESSAGE, PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + THROTTLING_EXCEPTION_MESSAGE, +}; +use serde_json::{Value, json}; + +use crate::AppState; + +/// Auth stub returning a fixed user identity without SigV4, so the test drives +/// the handler below the signature layer while the throttle segment, the +/// dispatch and the response building run as in production. `dev_mode` opens +/// the IAM decision for the authenticated caller. +struct StubAuth { + account_id: String, +} + +#[async_trait::async_trait] +impl AuthProvider for StubAuth { + async fn authenticate( + &self, + _headers: &HeaderMap, + _body: &[u8], + ) -> Result { + Ok(AuthIdentity::User { + account_id: self.account_id.clone(), + user_name: "dev".to_owned(), + }) + } +} + +fn cache_cfg(name: &'static str) -> extenddb_cache::SwrCacheConfig { + extenddb_cache::SwrCacheConfig { + ttl: std::time::Duration::from_secs(60), + soft_ttl: std::time::Duration::from_secs(30), + negative_ttl: std::time::Duration::from_secs(5), + max_entries: 128, + name, + } +} + +/// An `AppState` on a fresh in-memory SQLite engine with a bootstrapped +/// catalog, the stub auth bound to the default account, throttling on, and +/// `dev_mode` on. Returns the state and the account id the stub answers with, +/// so the expected ARN can be formed. +async fn build_state() -> (Arc, String) { + let _ = extenddb_storage::set_backend(extenddb_storage_sqlite::backend()); + let config = extenddb_storage_sqlite::SqliteConfig { + path: ":memory:".to_owned(), + pool_size: 2, + }; + let mut options = extenddb_storage::server_components::ServerComponentsOptions::default(); + options.bootstrap_if_uninitialized = true; + let components = extenddb_storage::create_server_components(&config, "us-east-1", options) + .await + .expect("in-memory server components"); + let account_id = components + .catalog_store + .default_account_id() + .await + .expect("default account query") + .expect("bootstrapped default account"); + + let authz_cache = Arc::new(crate::CachedAuthzStore::pass_through( + components.catalog_store.clone() + as Arc, + crate::AuthzCacheConfig { + identity_policies: cache_cfg("identity_policies"), + group_policies: cache_cfg("group_policies"), + boundary: cache_cfg("boundary"), + principal_tags: cache_cfg("principal_tags"), + resource_tags: cache_cfg("resource_tags"), + session_data: cache_cfg("session_data"), + }, + )); + let table_key_info_cache = Arc::new(crate::CachedTableKeyInfoStore::pass_through( + components.engine.clone(), + cache_cfg("table_key_info"), + )); + let limits = Arc::new(extenddb_core::limits::LimitsConfig::default()); + let empty_paths: Arc<[Arc]> = Arc::from(Vec::new()); + let throttle = Arc::new(extenddb_core::throttle::ThrottleManager::new( + limits.per_account_max_rcu, + limits.per_account_max_wcu, + true, + )); + + let state = Arc::new(AppState { + storage: components.engine, + backup_runtime: Arc::new(extenddb_engine::BackupRuntime::new(1)), + auth: Arc::new(StubAuth { + account_id: account_id.clone(), + }), + throttle, + limits, + region: Arc::from("us-east-1"), + server_addr: "localhost:0".to_owned(), + catalog_store: Some(components.catalog_store), + version_info: Arc::from("test"), + metrics: Arc::new(extenddb_core::metrics::MetricsCollector::new()), + tls_enabled: false, + request_timeout: std::time::Duration::from_secs(30), + dev_mode: true, + import_paths: empty_paths.clone(), + export_paths: empty_paths, + auth_cache: extenddb_auth::AuthCacheRegistry::empty(), + authz_cache, + table_key_info_cache, + config_entries: Vec::new(), + docs_store: None, + admission: crate::registration::Admission::default(), + }); + (state, account_id) +} + +async fn call(state: &Arc, operation: &str, body: Value) -> (u16, Value) { + let mut headers = HeaderMap::new(); + headers.insert( + "x-amz-target", + format!("DynamoDB_20120810.{operation}") + .parse() + .expect("target header"), + ); + let response = super::handle_request( + State(state.clone()), + "/".parse().expect("uri"), + axum::extract::ConnectInfo(std::net::SocketAddr::from(([127, 0, 0, 1], 40000))), + headers, + Ok(Bytes::from(body.to_string())), + ) + .await; + let status = response.status().as_u16(); + let bytes = axum::body::to_bytes(response.into_body(), 1 << 20) + .await + .expect("read body"); + let body: Value = serde_json::from_slice(&bytes).expect("json body"); + (status, body) +} + +/// Create `table` with the given billing fields and wait for ACTIVE. No +/// worker runs in this test, so the CREATING to ACTIVE transition is driven +/// here. +async fn create_table(state: &Arc, table: &str, billing: Value) { + let mut create = json!({ + "TableName": table, + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}], + }); + for (k, v) in billing.as_object().expect("billing object") { + create[k] = v.clone(); + } + let (status, body) = call(state, "CreateTable", create).await; + assert_eq!(status, 200, "{body}"); + let describe = json!({"TableName": table}); + for _ in 0..200 { + state + .storage + .process_control_plane_transitions() + .await + .expect("transitions"); + let (_, body) = call(state, "DescribeTable", describe.clone()).await; + if body["Table"]["TableStatus"] == "ACTIVE" { + return; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + panic!("table {table} did not become ACTIVE"); +} + +fn arn(account_id: &str, table: &str) -> String { + format!("arn:aws:dynamodb:us-east-1:{account_id}:table/{table}") +} + +fn item(size: usize) -> Value { + json!({"pk": {"S": "k"}, "v": {"S": "x".repeat(size)}}) +} + +/// A 1 WCU table starts with one second of burst; writes past it are refused +/// with the provisioned class, `ThrottlingReasons` (capital T), the write +/// reason and the table ARN formed from the server region and the account. +#[tokio::test] +async fn provisioned_write_throttle_names_the_table_arn() { + let (state, account_id) = build_state().await; + let table = "throttled-writes"; + create_table( + &state, + table, + json!({"ProvisionedThroughput": {"ReadCapacityUnits": 1, "WriteCapacityUnits": 1}}), + ) + .await; + // The manager is drained directly, far past the one second of burst, + // rather than by many writes, so the test does not depend on timing. + state.throttle.consume(&account_id, table, 0.0, 1.0e9); + let (status, body) = call( + &state, + "PutItem", + json!({"TableName": table, "Item": item(16)}), + ) + .await; + assert_eq!(status, 400, "{body}"); + assert_eq!( + body, + json!({ + "__type": "com.amazonaws.dynamodb.v20120810#ProvisionedThroughputExceededException", + "message": PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + "ThrottlingReasons": [{ + "reason": "TableWriteProvisionedThroughputExceeded", + "resource": arn(&account_id, table), + }], + }) + ); +} + +/// A read refusal names the read reason. +#[tokio::test] +async fn provisioned_read_throttle_names_the_read_reason() { + let (state, account_id) = build_state().await; + let table = "throttled-reads"; + create_table( + &state, + table, + json!({"ProvisionedThroughput": {"ReadCapacityUnits": 1, "WriteCapacityUnits": 1}}), + ) + .await; + state.throttle.consume(&account_id, table, 1.0e9, 0.0); + let (status, body) = call( + &state, + "GetItem", + json!({"TableName": table, "Key": {"pk": {"S": "k"}}}), + ) + .await; + assert_eq!(status, 400, "{body}"); + assert_eq!( + body["__type"], + "com.amazonaws.dynamodb.v20120810#ProvisionedThroughputExceededException" + ); + assert_eq!( + body["ThrottlingReasons"], + json!([{ + "reason": "TableReadProvisionedThroughputExceeded", + "resource": arn(&account_id, table), + }]) + ); +} + +/// A hot key on an on-demand table: the write carries `throttlingReasons` +/// (lower t) in the availability namespace; the read carries no reasons list. +#[tokio::test] +async fn on_demand_hot_key_write_names_the_key_range_and_read_carries_no_reasons() { + let (state, account_id) = build_state().await; + let table = "hot-key"; + create_table(&state, table, json!({"BillingMode": "PAY_PER_REQUEST"})).await; + // Drain the partition bucket for key "k" in both directions and leave + // the table bucket full: the drain runs while the table is not + // registered, and the request registers it again from DescribeTable, as + // after a restart. + state.throttle.remove_table(&account_id, table); + state + .throttle + .consume_with_partition(&account_id, table, 1.0e9, 1.0e9, Some("k")); + let (status, body) = call( + &state, + "PutItem", + json!({"TableName": table, "Item": item(16)}), + ) + .await; + assert_eq!(status, 400, "{body}"); + assert_eq!( + body, + json!({ + "__type": "com.amazon.coral.availability#ThrottlingException", + "message": THROTTLING_EXCEPTION_MESSAGE, + "throttlingReasons": [{ + "reason": "TableWriteKeyRangeThroughputExceeded", + "resource": arn(&account_id, table), + }], + }) + ); + let (status, body) = call( + &state, + "GetItem", + json!({"TableName": table, "Key": {"pk": {"S": "k"}}}), + ) + .await; + assert_eq!(status, 400, "{body}"); + assert_eq!( + body, + json!({ + "__type": "com.amazon.coral.availability#ThrottlingException", + "message": THROTTLING_EXCEPTION_MESSAGE, + }) + ); +} + +/// An on-demand table created with `OnDemandThroughput` caps is sized by the +/// caps and refuses with the caps message and limit. +#[tokio::test] +async fn on_demand_caps_throttle_names_the_max_on_demand_limit() { + let (state, account_id) = build_state().await; + let table = "capped"; + create_table( + &state, + table, + json!({ + "BillingMode": "PAY_PER_REQUEST", + "OnDemandThroughput": {"MaxReadRequestUnits": 1, "MaxWriteRequestUnits": 1}, + }), + ) + .await; + state.throttle.consume(&account_id, table, 1.0e9, 1.0e9); + for (operation, body, reason) in [ + ( + "Query", + json!({ + "TableName": table, + "KeyConditionExpression": "pk = :p", + "ExpressionAttributeValues": {":p": {"S": "k"}}, + }), + "TableReadMaxOnDemandThroughputExceeded", + ), + ( + "PutItem", + json!({"TableName": table, "Item": item(16)}), + "TableWriteMaxOnDemandThroughputExceeded", + ), + ] { + let (status, got) = call(&state, operation, body).await; + assert_eq!(status, 400, "{operation}: {got}"); + assert_eq!( + got, + json!({ + "__type": "com.amazon.coral.availability#ThrottlingException", + "message": MAX_ON_DEMAND_THROUGHPUT_MESSAGE, + "throttlingReasons": [{ + "reason": reason, + "resource": arn(&account_id, table), + }], + }), + "{operation}" + ); + } +} + +/// A table capped in one direction reports the caps body only for a refusal +/// in that direction; the other direction is the default ceiling's body. +#[tokio::test] +async fn half_capped_table_reports_the_cap_for_its_direction_only() { + let (state, account_id) = build_state().await; + let table = "half-capped"; + create_table( + &state, + table, + json!({ + "BillingMode": "PAY_PER_REQUEST", + "OnDemandThroughput": {"MaxWriteRequestUnits": 1}, + }), + ) + .await; + // Drain the write cap of 1 and the default read ceiling of 12,000. + state.throttle.consume(&account_id, table, 1.0e9, 1.0e9); + let (status, body) = call( + &state, + "PutItem", + json!({"TableName": table, "Item": item(16)}), + ) + .await; + assert_eq!(status, 400, "{body}"); + assert_eq!(body["message"], MAX_ON_DEMAND_THROUGHPUT_MESSAGE); + assert_eq!( + body["throttlingReasons"][0]["reason"], + "TableWriteMaxOnDemandThroughputExceeded" + ); + let (status, body) = call( + &state, + "GetItem", + json!({"TableName": table, "Key": {"pk": {"S": "k"}}}), + ) + .await; + assert_eq!(status, 400, "{body}"); + assert_eq!(body["message"], THROTTLING_EXCEPTION_MESSAGE); + assert_eq!( + body["throttlingReasons"][0]["reason"], + "TableReadAccountLimitExceeded" + ); +} + +/// The account bucket can refuse a request whose table the engine has never +/// seen. A `TableName` that is the ARN of a table in this account and Region +/// names that table in the reasons list. +#[tokio::test] +async fn account_throttle_reason_names_the_table_of_an_arn() { + let (state, account_id) = build_state().await; + // Drain the account aggregate (its limits are the per-account maxima). + state.throttle.consume(&account_id, "any", 1.0e9, 1.0e9); + let (status, body) = call( + &state, + "GetItem", + json!({"TableName": arn(&account_id, "absent"), "Key": {"pk": {"S": "k"}}}), + ) + .await; + assert_eq!(status, 400, "{body}"); + assert_eq!( + body["__type"], + "com.amazonaws.dynamodb.v20120810#RequestLimitExceeded" + ); + assert_eq!( + body["ThrottlingReasons"], + json!([{"reason": "TableReadAccountLimitExceeded", "resource": arn(&account_id, "absent")}]) + ); +} + +/// A `TableName` outside the table name rules is not throttled: with the +/// account bucket drained, the server answers it as it did with capacity +/// left, and with no reasons list. The service refuses such a name before +/// any throttle (measured 2026-11-25 with GetItem and PutItem, twice each). +#[tokio::test] +async fn names_outside_the_table_name_rules_are_not_throttled() { + let (state, account_id) = build_state().await; + let long = "a".repeat(256); + let other_region = format!("arn:aws:dynamodb:eu-west-1:{account_id}:table/absent"); + let mut requests = Vec::new(); + for name in ["ab", "", long.as_str(), other_region.as_str()] { + requests.push(( + "GetItem", + json!({"TableName": name, "Key": {"pk": {"S": "k"}}}), + )); + requests.push(("PutItem", json!({"TableName": name, "Item": item(16)}))); + } + let mut with_capacity = Vec::new(); + for (operation, request) in &requests { + with_capacity.push(call(&state, operation, request.clone()).await); + } + state.throttle.consume(&account_id, "any", 1.0e9, 1.0e9); + for ((operation, request), before) in requests.iter().zip(&with_capacity) { + let drained = call(&state, operation, request.clone()).await; + assert_eq!(&drained, before, "{operation} {request}"); + assert_eq!(drained.0, 400, "{operation} {request}"); + } +} + +/// With capacity available the same requests succeed, so the refusals above +/// come from the throttle segment and not from the request shape. +#[tokio::test] +async fn requests_with_capacity_are_served() { + let (state, _) = build_state().await; + let table = "served"; + create_table( + &state, + table, + json!({"ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}}), + ) + .await; + let (status, body) = call( + &state, + "PutItem", + json!({"TableName": table, "Item": item(16)}), + ) + .await; + assert_eq!(status, 200, "{body}"); + let (status, body) = call( + &state, + "GetItem", + json!({"TableName": table, "Key": {"pk": {"S": "k"}}}), + ) + .await; + assert_eq!(status, 200, "{body}"); + assert_eq!(body["Item"]["pk"], json!({"S": "k"})); +} diff --git a/crates/server/src/response.rs b/crates/server/src/response.rs index 1b26cd378..8ea195307 100755 --- a/crates/server/src/response.rs +++ b/crates/server/src/response.rs @@ -37,9 +37,10 @@ pub(crate) fn success_response(body: &Value, request_id: &str) -> Response { /// key `error_document` picks. REQ-ERR-003: Omit the message field when empty /// (real `DynamoDB` behavior, verified 2026-05-04). pub(crate) fn error_response(error: &DynamoDbError, request_id: &str) -> Response { - // The body shape (`__type`, optional message, `CancellationReasons`, `Item`) - // is built by the shared `error_document` helper so the wire body and the - // in-process body come from the same code; this transport adds the HTTP status and headers. + // The body shape (`__type`, optional message, `CancellationReasons`, the + // throttle reasons list, `Item`) is built by the shared `error_document` + // helper so the wire body and the in-process body come from the same code; + // this transport adds the HTTP status and headers. let body = error_document(error); let body_bytes = serde_json::to_vec(&body).unwrap_or_else(|_| SERIALIZATION_FAILURE_BODY.to_vec()); diff --git a/crates/server/src/throttle_helpers.rs b/crates/server/src/throttle_helpers.rs index 468f63a54..e6b353141 100755 --- a/crates/server/src/throttle_helpers.rs +++ b/crates/server/src/throttle_helpers.rs @@ -7,6 +7,7 @@ //! request handling: classifying operations, extracting throughput from //! responses, and managing bucket lifecycle. +use extenddb_core::error::DynamoDbError; use extenddb_core::throttle::ThrottleManager; use serde_json::Value; @@ -19,7 +20,16 @@ pub(crate) fn table_description_to_throughput( .as_ref() .is_some_and(|bms| bms.billing_mode == extenddb_core::types::BillingMode::PayPerRequest); if is_on_demand { - extenddb_core::throttle::TableThroughput::on_demand() + // A table whose OnDemandThroughput caps are set is sized by them; the + // service names that limit on a throttle (MaxOnDemandThroughputExceeded, + // measured 2026-10-24), so the manager must know which case it is. + match desc.on_demand_throughput.as_ref() { + Some(caps) => extenddb_core::throttle::TableThroughput::on_demand_capped( + caps.max_read_request_units, + caps.max_write_request_units, + ), + None => extenddb_core::throttle::TableThroughput::on_demand(), + } } else { extenddb_core::throttle::TableThroughput::provisioned( desc.provisioned_throughput.read_capacity_units, @@ -87,7 +97,14 @@ fn extract_throughput_from_response( .is_some_and(|bm| bm == "PAY_PER_REQUEST"); if is_on_demand { - return Some(extenddb_core::throttle::TableThroughput::on_demand()); + // Caps set on the table size its buckets; see table_description_to_throughput. + return Some(match desc.get("OnDemandThroughput") { + Some(caps) => extenddb_core::throttle::TableThroughput::on_demand_capped( + caps.get("MaxReadRequestUnits").and_then(Value::as_i64), + caps.get("MaxWriteRequestUnits").and_then(Value::as_i64), + ), + None => extenddb_core::throttle::TableThroughput::on_demand(), + }); } let pt = desc.get("ProvisionedThroughput")?; @@ -116,3 +133,306 @@ pub(crate) fn extract_partition_value(input: &Value, operation: &str) -> Option< let (_, val) = type_obj.iter().next()?; Some(val.as_str().unwrap_or_default().to_owned()) } + +/// The throttle error the service sends for a refusal by `cause` on a table +/// billed as the cause says, naming `table_arn` as the throttled resource. +/// +/// Measured against the service (2026-10-20 and 2026-10-24, two Regions): a +/// provisioned table's own capacity gives `ProvisionedThroughputExceededException` +/// with `Table{Read|Write}ProvisionedThroughputExceeded` on every read and +/// write operation; a hot partition key on an on-demand table gives +/// `ThrottlingException` with `TableWriteKeyRangeThroughputExceeded` on a +/// write and no reasons list at all on a read; an on-demand table at its +/// `OnDemandThroughput` caps gives `ThrottlingException` with the caps +/// message and `Table{Read|Write}MaxOnDemandThroughputExceeded`. A hot key on a +/// provisioned table was captured once on 2026-10-20 (a `BatchWriteItem`): +/// the provisioned class, the table message and +/// `TableWriteKeyRangeThroughputExceeded`; the read form follows the +/// documented grammar. Documented in the API Reference (ThrottlingReason, +/// PutItem Errors; read 2026-10-20) and not produced by the probes: an +/// on-demand table past its default ceiling and the account aggregate carry +/// `Table{Read|Write}AccountLimitExceeded`, on `ThrottlingException` and +/// `RequestLimitExceeded` respectively. +pub(crate) fn throttle_error( + cause: extenddb_core::throttle::ThrottleCause, + read: bool, + table_arn: &str, +) -> DynamoDbError { + use extenddb_core::error::{ + MAX_ON_DEMAND_THROUGHPUT_MESSAGE, PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + REQUEST_LIMIT_EXCEEDED_MESSAGE, THROTTLING_EXCEPTION_MESSAGE, ThrottlingReason, + }; + use extenddb_core::throttle::ThrottleCause; + let op = if read { "Read" } else { "Write" }; + let reason = |limit: &str| { + vec![ThrottlingReason { + reason: format!("Table{op}{limit}"), + resource: table_arn.to_owned(), + }] + }; + match cause { + ThrottleCause::Table { + on_demand: false, .. + } => DynamoDbError::provisioned_throughput_exceeded( + PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + reason("ProvisionedThroughputExceeded"), + ), + ThrottleCause::Partition { on_demand: false } => { + DynamoDbError::provisioned_throughput_exceeded( + PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + reason("KeyRangeThroughputExceeded"), + ) + } + // A hot-key read on an on-demand table carries no reasons list + // (5,615 of 5,615 captures); the write form names the key range. + ThrottleCause::Partition { on_demand: true } if read => { + DynamoDbError::throttling(THROTTLING_EXCEPTION_MESSAGE, vec![]) + } + ThrottleCause::Partition { on_demand: true } => DynamoDbError::throttling( + THROTTLING_EXCEPTION_MESSAGE, + reason("KeyRangeThroughputExceeded"), + ), + // `capped` is the refusing direction's own cap, so a table capped in + // one direction sends the default-ceiling body for the other. + ThrottleCause::Table { + on_demand: true, + capped: true, + } => DynamoDbError::throttling( + MAX_ON_DEMAND_THROUGHPUT_MESSAGE, + reason("MaxOnDemandThroughputExceeded"), + ), + ThrottleCause::Table { + on_demand: true, + capped: false, + } => { + DynamoDbError::throttling(THROTTLING_EXCEPTION_MESSAGE, reason("AccountLimitExceeded")) + } + ThrottleCause::Account => DynamoDbError::request_limit_exceeded( + REQUEST_LIMIT_EXCEEDED_MESSAGE, + reason("AccountLimitExceeded"), + ), + } +} + +#[cfg(test)] +mod extract_throughput_tests { + use extenddb_core::types::{ + BillingMode, BillingModeSummary, OnDemandThroughput, TableDescription, + }; + use serde_json::json; + + use super::{extract_throughput_from_response, table_description_to_throughput}; + + fn on_demand_description(caps: Option) -> TableDescription { + TableDescription { + billing_mode_summary: Some(BillingModeSummary { + billing_mode: BillingMode::PayPerRequest, + last_update_to_pay_per_request_date_time: None, + }), + on_demand_throughput: caps, + ..TableDescription::default() + } + } + + // The typed path registers a table lazily after a restart; it reads the + // caps the same way the response-body path does. + #[test] + fn typed_on_demand_description_with_caps_is_sized_by_them() { + let t = table_description_to_throughput(&on_demand_description(Some(OnDemandThroughput { + max_read_request_units: Some(1), + max_write_request_units: Some(2), + }))); + assert_eq!((t.rcu, t.wcu, t.on_demand), (1.0, 2.0, true)); + assert!(t.read_capped && t.write_capped); + } + + #[test] + fn typed_on_demand_description_without_caps_or_with_removed_caps_keeps_the_defaults() { + let defaults = extenddb_core::throttle::TableThroughput::on_demand(); + for caps in [ + None, + Some(OnDemandThroughput { + max_read_request_units: Some(-1), + max_write_request_units: None, + }), + ] { + let t = table_description_to_throughput(&on_demand_description(caps)); + assert!(t.on_demand && !t.read_capped && !t.write_capped); + assert_eq!((t.rcu, t.wcu), (defaults.rcu, defaults.wcu)); + } + } + + #[test] + fn provisioned_description_gives_its_units() { + let t = extract_throughput_from_response(&json!({ + "TableDescription": {"ProvisionedThroughput": {"ReadCapacityUnits": 7, "WriteCapacityUnits": 3}} + })) + .expect("throughput"); + assert_eq!((t.rcu, t.wcu, t.on_demand), (7.0, 3.0, false)); + assert!(!t.read_capped && !t.write_capped); + } + + #[test] + fn on_demand_description_without_caps_gives_the_default_ceilings() { + let t = extract_throughput_from_response(&json!({ + "Table": {"BillingModeSummary": {"BillingMode": "PAY_PER_REQUEST"}} + })) + .expect("throughput"); + assert!(t.on_demand && !t.read_capped && !t.write_capped); + let defaults = extenddb_core::throttle::TableThroughput::on_demand(); + assert_eq!((t.rcu, t.wcu), (defaults.rcu, defaults.wcu)); + } + + #[test] + fn on_demand_description_with_caps_is_sized_by_them() { + let t = extract_throughput_from_response(&json!({ + "Table": { + "BillingModeSummary": {"BillingMode": "PAY_PER_REQUEST"}, + "OnDemandThroughput": {"MaxReadRequestUnits": 1, "MaxWriteRequestUnits": 2} + } + })) + .expect("throughput"); + assert_eq!((t.rcu, t.wcu, t.on_demand), (1.0, 2.0, true)); + assert!(t.read_capped && t.write_capped); + } +} + +#[cfg(test)] +mod throttle_error_tests { + use extenddb_core::error::{ + DynamoDbError, MAX_ON_DEMAND_THROUGHPUT_MESSAGE, PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + REQUEST_LIMIT_EXCEEDED_MESSAGE, THROTTLING_EXCEPTION_MESSAGE, + }; + use extenddb_core::throttle::ThrottleCause; + + use super::throttle_error; + + const ARN: &str = "arn:aws:dynamodb:us-east-1:123456789012:table/T"; + + fn parts(err: &DynamoDbError) -> (&'static str, String, Vec<(String, String)>) { + let class = match err { + DynamoDbError::ProvisionedThroughputExceededException { .. } => "provisioned", + DynamoDbError::ThrottlingException { .. } => "throttling", + DynamoDbError::RequestLimitExceeded { .. } => "request-limit", + other => panic!("not a throttle error: {other:?}"), + }; + let reasons = err + .throttling_reasons() + .expect("throttle error") + .iter() + .map(|r| (r.reason.clone(), r.resource.clone())) + .collect(); + (class, err.message().to_owned(), reasons) + } + + /// Every arm of `throttle_error`, both directions: the error class, the + /// message, the reason and the resource. + #[test] + fn maps_every_cause_and_direction() { + let table = |on_demand, capped| ThrottleCause::Table { on_demand, capped }; + let one = |limit: &str| vec![(limit.to_owned(), ARN.to_owned())]; + // (cause, read, class, message, reasons) + type Case = ( + ThrottleCause, + bool, + &'static str, + &'static str, + Vec<(String, String)>, + ); + let cases: Vec = vec![ + ( + table(false, false), + true, + "provisioned", + PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + one("TableReadProvisionedThroughputExceeded"), + ), + ( + table(false, false), + false, + "provisioned", + PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + one("TableWriteProvisionedThroughputExceeded"), + ), + ( + ThrottleCause::Partition { on_demand: false }, + true, + "provisioned", + PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + one("TableReadKeyRangeThroughputExceeded"), + ), + ( + ThrottleCause::Partition { on_demand: false }, + false, + "provisioned", + PROVISIONED_THROUGHPUT_EXCEEDED_MESSAGE, + one("TableWriteKeyRangeThroughputExceeded"), + ), + ( + ThrottleCause::Partition { on_demand: true }, + true, + "throttling", + THROTTLING_EXCEPTION_MESSAGE, + vec![], + ), + ( + ThrottleCause::Partition { on_demand: true }, + false, + "throttling", + THROTTLING_EXCEPTION_MESSAGE, + one("TableWriteKeyRangeThroughputExceeded"), + ), + ( + table(true, true), + true, + "throttling", + MAX_ON_DEMAND_THROUGHPUT_MESSAGE, + one("TableReadMaxOnDemandThroughputExceeded"), + ), + ( + table(true, true), + false, + "throttling", + MAX_ON_DEMAND_THROUGHPUT_MESSAGE, + one("TableWriteMaxOnDemandThroughputExceeded"), + ), + ( + table(true, false), + true, + "throttling", + THROTTLING_EXCEPTION_MESSAGE, + one("TableReadAccountLimitExceeded"), + ), + ( + table(true, false), + false, + "throttling", + THROTTLING_EXCEPTION_MESSAGE, + one("TableWriteAccountLimitExceeded"), + ), + ( + ThrottleCause::Account, + true, + "request-limit", + REQUEST_LIMIT_EXCEEDED_MESSAGE, + one("TableReadAccountLimitExceeded"), + ), + ( + ThrottleCause::Account, + false, + "request-limit", + REQUEST_LIMIT_EXCEEDED_MESSAGE, + one("TableWriteAccountLimitExceeded"), + ), + ]; + for (cause, read, class, message, reasons) in cases { + let err = throttle_error(cause, read, ARN); + assert_eq!( + parts(&err), + (class, message.to_owned(), reasons), + "{cause:?} read={read}" + ); + assert_eq!(err.status_code(), 400); + } + } +} diff --git a/docs/design/06-component-server.md b/docs/design/06-component-server.md index 46cd8c524..492542df2 100755 --- a/docs/design/06-component-server.md +++ b/docs/design/06-component-server.md @@ -625,7 +625,7 @@ struct TokenBucketState { } ``` -The handler calls `core::capacity::calculator` to compute consumed RCU/WCU, then calls `ThroughputTracker::consume()` to deduct tokens. If insufficient tokens, returns `ProvisionedThroughputExceededException`. +The handler calls `core::capacity::calculator` to compute consumed RCU/WCU, then calls `ThroughputTracker::consume()` to deduct tokens. If insufficient tokens, returns the throttle error for the refusing bucket and billing mode (`throttle_helpers::throttle_error`): the provisioned class, `ThrottlingException` or `RequestLimitExceeded`, with the table ARN and the limit in the reasons list where the service sends one; see differences-from-dynamodb.md. --- diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index a88689353..7d2c4717e 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -207,9 +207,11 @@ alone, with the same wording. For PartiQL this holds in `ExecuteStatement`, | Area | DynamoDB | ExtendDB | |------|----------|------| | Provisioned throughput | Token bucket per table/partition | Token bucket per table/partition, matching DynamoDB's burst and refill behavior | -| On-demand capacity | Automatic scaling | Fixed initial burst capacity (4000 WCU / 12000 RCU), no auto-scaling | +| On-demand capacity | Automatic scaling | Fixed initial burst capacity (4000 WCU / 12000 RCU), no auto-scaling; a table with `OnDemandThroughput` caps is sized by the caps, per direction; the bucket starts with one second of the rate and accumulates unused capacity up to 300 seconds of it | | Warm throughput | Pre-provisions partitions to the requested read and write units; raising it is a long-running operation (`Status: UPDATING` for minutes, the previous values reported meanwhile); a request above the account's table maximum is `LimitExceededException` | Stored and reported with the same shape, defaults and validation so clients that read it (the Terraform AWS provider since 6.13.0) work: the previous values are reported with `Status: UPDATING` for `control_plane_delay_seconds` after a change, then the new values `ACTIVE`; a decrease is measured against the reported values, as on the service. Nothing acts on the values: no pre-warming and no scaling at the database level. The account maximum is not known to ExtendDB and is not enforced. A provisioned table whose warm throughput was never set, or was set on one side only, reports its new units at once after a capacity change, where the service reports the old units until the table is `ACTIVE`. Switching a table to `PAY_PER_REQUEST` stores 12000 read and 4000 write units where its warm throughput is lower, and the stored values stay after a switch back to `PROVISIONED`, as on the service; the response to the switch reads the new values with `Status: UPDATING` for `control_plane_delay_seconds`, where the service answers with the previous values and `Status: ACTIVE` | | Throttling | Always on; throttles requests that exceed provisioned/burst capacity. No setting to disable | Configurable via `throttling_enabled` runtime setting (default: `true`) | +| Throttle error bodies | A throttle names the throttled resource and the limit. A provisioned table's own capacity is `ProvisionedThroughputExceededException` with `ThrottlingReasons: [{reason: Table{Read\|Write}ProvisionedThroughputExceeded, resource: }]` on every read and write operation; a hot key on an on-demand table is `ThrottlingException` in the `com.amazon.coral.availability#` namespace with `throttlingReasons` (lower t) naming `TableWriteKeyRangeThroughputExceeded` on a write and no reasons list on a read; an on-demand table at its `OnDemandThroughput` caps is `ThrottlingException` with the message `Throughput exceeds the maximum OnDemandThroughput configured on table or index` and `Table{Read\|Write}MaxOnDemandThroughputExceeded`. Measured 2026-10-20 (435 bodies, one Region) and 2026-10-24 (9,622 bodies, two Regions). No `x-amz-retry-after` header | The throttle covers GetItem, PutItem, UpdateItem, DeleteItem, Query and Scan, the operations whose request names one table in `TableName`, and sends the same classes, namespaces, messages, field names and reasons for the table, hot-key and caps buckets. BatchGetItem, BatchWriteItem, TransactGetItems, TransactWriteItems and the PartiQL operations are not throttled. The account aggregate bucket sends `RequestLimitExceeded` with `Table{Read\|Write}AccountLimitExceeded`, and an on-demand table past its default ceiling sends `ThrottlingException` with the same reason: both follow the API Reference and were not produced by the measurements. A hot key on a provisioned table names `Table{Read\|Write}KeyRangeThroughputExceeded` with the provisioned class and message; the write form was captured once on 2026-10-20, the read form follows the documented grammar | +| Index back-pressure | A base-table write held back by an under-provisioned global secondary index is throttled with `IndexWriteProvisionedThroughputExceeded`, the index ARN and a message naming global secondary indexes; an index read past the index's capacity names `IndexReadProvisionedThroughputExceeded` and the index ARN (measured 2026-10-24: 104 index-write bodies, 648 index-read bodies) | Not modelled: the token buckets are per table and per partition key, with no per-index capacity | ## Transactions diff --git a/docs/dynamodb-limits.md b/docs/dynamodb-limits.md index 92bfc362c..89a152f62 100755 --- a/docs/dynamodb-limits.md +++ b/docs/dynamodb-limits.md @@ -17,8 +17,8 @@ Source: [AWS DynamoDB Service Quotas](https://docs.aws.amazon.com/amazondynamodb |-------|---------------|--------|-------| | Per-table RCU (provisioned) | 40,000 | Enforced | `LimitsConfig::per_table_max_rcu`, configurable | | Per-table WCU (provisioned) | 40,000 | Enforced | `LimitsConfig::per_table_max_wcu`, configurable | -| Per-table read request units (on-demand) | 40,000 | N/A | ExtendDB does not throttle on-demand reads | -| Per-table write request units (on-demand) | 40,000 | N/A | ExtendDB does not throttle on-demand writes | +| Per-table read request units (on-demand) | 40,000 | Enforced | Default ceiling 12,000 RCU, or the `OnDemandThroughput` read cap when set; the bucket starts with one second of the rate and accumulates unused capacity up to 300 seconds of it | +| Per-table write request units (on-demand) | 40,000 | Enforced | Default ceiling 4,000 WCU, or the `OnDemandThroughput` write cap when set; the bucket starts with one second of the rate and accumulates unused capacity up to 300 seconds of it | | Per-account RCU (provisioned) | 80,000 | Enforced | `LimitsConfig::per_account_max_rcu`, configurable | | Per-account WCU (provisioned) | 80,000 | Enforced | `LimitsConfig::per_account_max_wcu`, configurable | | Minimum throughput per table/GSI | 1 RCU / 1 WCU | Enforced | `validate_provisioned_throughput` rejects < 1 | diff --git a/docs/manuals/10-security-model.md b/docs/manuals/10-security-model.md index b3569ef53..ef52ae945 100755 --- a/docs/manuals/10-security-model.md +++ b/docs/manuals/10-security-model.md @@ -321,7 +321,7 @@ A password can be guessed against one user from many addresses at 5 attempts per ## Provisioned Throughput Throttling -extenddb includes a token bucket rate limiter for provisioned throughput enforcement. When `server.throttling_enabled = true` in `extenddb.toml`, read and write requests are throttled against the table's provisioned RCU/WCU limits. Requests that exceed the limit receive `ProvisionedThroughputExceededException` (HTTP 400), matching real DynamoDB behavior. +extenddb includes a token bucket rate limiter for provisioned throughput enforcement. When `server.throttling_enabled = true` in `extenddb.toml`, read and write requests are throttled against the table's provisioned RCU/WCU limits. Requests that exceed the limit receive the throttle error the service sends for that bucket and billing mode (`ProvisionedThroughputExceededException` for provisioned capacity, `ThrottlingException` for an on-demand table at a hot key, at its default ceiling or at an `OnDemandThroughput` cap, `RequestLimitExceeded` for the account aggregate), HTTP 400, naming the throttled table and the limit in the reasons list where the service does (a hot-key read on an on-demand table carries none); see `differences-from-dynamodb.md`. Token buckets are purely in-memory operational state — not cached database state. They are recreated on server restart.