Skip to content

Engine=Kafka support for rack-aware consumption for Amazon MSK, IMDSv2 - #81323

Merged
alexey-milovidov merged 31 commits into
ClickHouse:masterfrom
ilejn:kafka_aws_az_aware
May 7, 2026
Merged

alexey-milovidov merged 31 commits into
ClickHouse:masterfrom
ilejn:kafka_aws_az_aware

Conversation

@ilejn

@ilejn ilejn commented Jun 4, 2025 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

  • Parameter kafka_autodetect_client_rack is introduced. If set, discover Availability Zone by cloud facilities and promoted as client.rack librdkafka parameter to avoid cross-zone communications.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Details

Handles #80445

Version info

  • Merged into: 26.5.1.409

@ilejn

ilejn commented Jun 10, 2025

Copy link
Copy Markdown
Contributor Author

Tested against AWS/MSK

@ilejn
ilejn marked this pull request as ready for review June 10, 2025 08:05
@ilejn

ilejn commented Jun 10, 2025

Copy link
Copy Markdown
Contributor Author

Handles #81402

@ilejn ilejn changed the title Engine=Kafka support for rack-aware consumption for Amazon MSK Engine=Kafka support for rack-aware consumption for Amazon MSK, IMDSv2 Jun 10, 2025
@GrigoryPervakov GrigoryPervakov added the can be tested Allows running workflows for external contributors label Jun 18, 2025
@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2025

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e13c788]

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jun 18, 2025
@ilejn

ilejn commented Jul 11, 2025

Copy link
Copy Markdown
Contributor Author

@zvonand , could you review this, please.

@zvonand zvonand left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, but I wonder if it somehow possible to add a test (an integration test mocking AWS or some smarter way)

Comment thread src/Storages/Kafka/KafkaSettings.cpp Outdated
DECLARE(String, kafka_sasl_mechanism, "", "SASL mechanism to use for authentication. Supported: GSSAPI, PLAIN, SCRAM-SHA-256, SCRAM-SHA-512, OAUTHBEARER.", 0) \
DECLARE(String, kafka_sasl_username, "", "SASL username for use with the PLAIN and SASL-SCRAM-.. mechanisms", 0) \
DECLARE(String, kafka_sasl_password, "", "SASL password for use with the PLAIN and SASL-SCRAM-.. mechanisms", 0) \
DECLARE(String, kafka_autodetect_client_rack, "", "Use cloud facilities to set client.rack to communicate with the nearest kafka replica. Supported: 'MSK' (for AWS)", 0) \

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe this setting itself can be an enum? (like StreamingHandleErrorMode )

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe this setting itself can be an enum? (like StreamingHandleErrorMode )

It was String in 1a498f5
@filimonov believes that on/off approach is better here.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Enum is ok. Maybe the AWS_MSK can be a better (less ambiguous) name

off / AWS_MSK and eventually others one day - like confluent_aws (i think it uses zone name not id as MSK, https://docs.confluent.io/operator/current/co-configure-rack-awareness.html)
maybe something for google managed kafka https://cloud.google.com/managed-service-for-apache-kafka/docs/overview etc.

@filimonov

Copy link
Copy Markdown
Contributor

Maybe would be nice to add a line to docs.

Official docs from AWS: https://aws.amazon.com/blogs/big-data/reduce-network-traffic-costs-of-your-amazon-msk-consumers-with-rack-awareness/ (you need to add replica.selector.class = org.apache.kafka.common.replica.RackAwareReplicaSelector to MSK cluster config, and broker.rack is configured automatically by MSK)

When configured properly that command

kafka-configs.sh --bootstrap-server boot-f1v.....amazonaws.com:9092  --describe --entity-type brokers -all  | grep -E '(All configs|replica.selector.class|broker.rack)'

Should output like like

All configs for broker 1 are:
  broker.rack=usw2-az2 sensitive=false synonyms={STATIC_BROKER_CONFIG:broker.rack=usw2-az2}
  replica.selector.class=org.apache.kafka.common.replica.RackAwareReplicaSelector sensitive=false synonyms={STATIC_BROKER_CONFIG:replica.selector.class=org.apache.kafka.common.replica.RackAwareReplicaSelector}

And then it should be enough to enable kafka_autodetect_client_rack='MSK'

@filimonov

Copy link
Copy Markdown
Contributor

LGTM, but I wonder if it somehow possible to add a test (an integration test mocking AWS or some smarter way)

Can be a bit tricky - we would need to mock IMDSv2 somewhere (+have a possibility to overwrite that ip in clickhouse code). And still it will not be an end-to-end test...

So the manual end-to-end test (which was done) is more important here.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It needs to be added to Kafka2.

@alexey-milovidov alexey-milovidov added the close in a month if not active This will be closed in case of no information label Oct 17, 2025
@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8845133]

Summary: ✅


AI Review

Summary

This PR adds kafka_autodetect_client_rack and wires client.rack autodetection via AWS/GCP/CLICKHOUSE providers, plus integration coverage and docs. The feature is useful, but there is still one backward-compatibility failure mode in IMDS handling and one observability issue in provider-attempt logging, so the PR should not be merged yet.

Findings

❌ Blockers

  • [src/IO/S3/Credentials.cpp:415-418] IMDSv2 token retrieval is only treated as optional when the HTTP call returns a non-200 response; transport/protocol exceptions from sendRequest / receiveResponse are not caught in the token phase and abort zone detection before the documented token-less fallback path runs. This can break environments where token calls fail but IMDSv1 metadata GET still works.
    • Suggested fix: catch token-request exceptions locally in getAvailabilityZoneOrException, log the exception, and continue with token-less metadata request.

⚠️ Majors

  • [src/IO/S3/Credentials.cpp:516-517] In AWS_ZONE_NAME_THEN_GCP_ZONE mode, failure logs always print AWS_ZONE_NAME_THEN_GCP_ZONE instead of the concrete provider attempted (AWS_ZONE_NAME or GCP_ZONE), which makes production troubleshooting materially harder.
    • Suggested fix: store provider enum/name alongside each getter and log that concrete provider in the catch path.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ❌ IMDSv1 fallback is not resilient to token-request exceptions
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ⚠️ rollout risk remains until fallback handling is fixed
Compilation time ✅
No large/binary files ✅
Performance & Safety
  • The blocking issue is a runtime failure-mode regression in metadata resolution, not a hot-path performance regression.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Handle token-phase exceptions in getAvailabilityZoneOrException and keep token-less availability-zone retrieval as an actual fallback path.
  2. Log the specific provider attempted in AWS_ZONE_NAME_THEN_GCP_ZONE failure messages.

@ilejn

ilejn commented Nov 5, 2025

Copy link
Copy Markdown
Contributor Author

It needs to be added to Kafka2.

@alexey-milovidov
This code is agnostic to kafka engine versions, it works with Kafka as well as with Kafka2 in exactly the same way.
I've added a test and IMDS mock.

What I don't like about this code, is how it coexists with PlacementInfo::getAvailabilityZone() .
E.g. PlacementInfo is able to get zone from availability_zone configuration parameter, but kafka specific stuff is not.

Comment thread src/IO/S3/Credentials.cpp Outdated
std::vector<std::pair<bool /* used if AUTO */, AZGetter>> az_getters =
{
/// order of getters reflects DB::S3::AZFacilities, except AUTO, which is skipped
{true, [](){return AWSEC2MetadataClient::getAWSZoneID();}}, /// AWS_ZONE_ID

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getRunningAvailabilityZone now tries AWS_ZONE_ID first for AZFacilities::AUTO, but CloudPlacementInfo::initialize calls S3::getRunningAvailabilityZone() with the default AUTO. Before this PR, that path returned AWS zone name (eu-central-1a); after this change it returns zone ID (euc1-az2), which changes placement.use_imds semantics globally (Keeper/ZooKeeper client rack selection and any other PlacementInfo consumers).

Can we keep the old default behavior for generic callers (e.g. AUTO = AWS_ZONE_NAME first), and use explicit AWS_ZONE_ID only for kafka_autodetect_client_rack?

ENGINE = MergeTree()
ORDER BY time;

{create_query_generator(kafka_table, "t UInt64, `e.x` String", brokers='kafka1:19092', topic_list=topname, consumer_group=topname, format='JSONEachRow', settings={'kafka_autodetect_client_rack':'AWS_ZONE_ID', 'input_format_import_nested_json':1})};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ This test only exercises kafka_autodetect_client_rack='AWS_ZONE_ID', but the setting now documents/support for AWS_ZONE_NAME, GCP_ZONE, CLICKHOUSE, and AUTO as well.

Given that provider ordering/selection is the risky part of this change, please add at least focused coverage for:

  • AUTO provider order/behavior,
  • CLICKHOUSE path,
  • one negative case (unknown facility logs error and does not set client.rack).

Without those, regressions in provider selection logic can slip through while this test still passes.

Comment thread src/Storages/Kafka/KafkaSettings.cpp Outdated
DECLARE(String, kafka_sasl_mechanism, "", "SASL mechanism to use for authentication. Supported: GSSAPI, PLAIN, SCRAM-SHA-256, SCRAM-SHA-512, OAUTHBEARER.", 0) \
DECLARE(String, kafka_sasl_username, "", "SASL username for use with the PLAIN and SASL-SCRAM-.. mechanisms", 0) \
DECLARE(String, kafka_sasl_password, "", "SASL password for use with the PLAIN and SASL-SCRAM-.. mechanisms", 0) \
DECLARE(String, kafka_autodetect_client_rack, "", "Automatically sets client.rack to prefer the nearest Kafka replicas. Supported values: 'AWS_ZONE_ID', 'AWS_ZONE_NAME', 'GCP_ZONE', 'CLICKHOUSE', 'AUTO'. Empty string disables the feature.", 0) \

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 The PR metadata currently says "currently supported value is MSK", but this implementation exposes AWS_ZONE_ID, AWS_ZONE_NAME, GCP_ZONE, CLICKHOUSE, and AUTO.

Please update the changelog entry text in the PR description so user-facing release notes match the actual setting contract.

LOG_ERROR(params.log, "Failed to determine client.rack via facility {}.", autodetect_rack);
}
else
LOG_ERROR(params.log, "Unknown kafka_autodetect_client_rack facility.");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ When the setting value is invalid we only log a generic message, but the log line omits the actual value and valid options. This makes operator debugging harder (especially with named collections) and hides typos.

Please include the provided value and expected facilities in the message, e.g. Unknown kafka_autodetect_client_rack facility '<value>'; expected one of AWS_ZONE_ID, AWS_ZONE_NAME, GCP_ZONE, CLICKHOUSE, AUTO.

Comment thread src/IO/S3/Credentials.cpp Outdated
if (token_response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK)
Poco::StreamCopier::copyToString(token_rs, token_str);
if (token_str.empty())
throw DB::Exception(ErrorCodes::AWS_ERROR, "Failed to get AWS availability zone (token). HTTP response code: {}", token_response.getStatus());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getAvailabilityZoneOrException now hard-requires an IMDSv2 token (/latest/api/token) and throws immediately when token fetch fails. Unlike AWSEC2MetadataClient::getDefaultCredentialsSecurely, this path has no fallback to IMDSv1 metadata reads.

That is a backward-compatibility regression for environments where token fetch is unavailable (older/custom metadata proxies, restrictive network policies, or IMDSv1-only compatibility setups): kafka_autodetect_client_rack and placement.use_imds can no longer detect AZ even though plain metadata GET would still work.

Please mirror the existing credential logic here: if token fetch fails with a non-fatal response, retry AZ request without the token header before giving up.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@filimonov , could you reconfirm that it is a good idea to abandon IMDSv1 completely?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"older/custom metadata proxies, restrictive network policies, or IMDSv1-only compatibility setups" - are those here now with us? In that room? :)

We are solving concrete task for nodes living in AWS infrastructure. In AWS infrastructure currently it's impossible to have v2 not working while v1 works (you can either forbid IMDS fully, or forbid v1, so i see no real life scenarios when fallback maybe useful).

Unless somebody will show usecase - that fallback to v1 sounds like YAGNI.

@pytest.mark.parametrize(
("autodetect_facility", "expected_rack", "topic_name"),
[
("AWS_ZONE_NAME_THEN_GCP_ZONE", "eu-central-1a", "zone_awareness_auto"),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ AUTO currently gets exercised only in the happy path where AWS metadata is available (endpoint.py always serves /latest/.../availability-zone), so this test never validates the fallback branch to GCP_ZONE.

Given the new provider-selection logic, the risky part is exactly the fallback order. Please add a focused case that makes AWS AZ lookup fail (for example by returning non-200 for AWS metadata endpoints) and verifies kafka_autodetect_client_rack='AWS_ZONE_NAME_THEN_GCP_ZONE' sets client.rack from /computeMetadata/v1/instance/zone.

def placement_availability_zone():
if SERVICE != "aws":
abort(404, "Not Found")
abort(404, "Not Found")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ This mock always returns 404 for /latest/meta-data/placement/availability-zone, so the suite never validates the direct AWS_ZONE_NAME path end-to-end (it only validates fallback behavior).

Please add one happy-path case where this endpoint returns a zone name (for example eu-central-1a) and assert kafka_autodetect_client_rack='AWS_ZONE_NAME' sets client.rack accordingly.

@clickhouse-gh

clickhouse-gh Bot commented May 5, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 93.18% (82/88) · Uncovered code

Full report · Diff report

@ilejn

ilejn commented May 7, 2026

Copy link
Copy Markdown
Contributor Author

Hello @alexey-milovidov , since it is your name is written on the red flag, could you have a look, please?

If I understand your request "It needs to be added to Kafka2" correctly, it is addressed, test for Kafka2 is created.

@alexey-milovidov
alexey-milovidov self-requested a review May 7, 2026 14:43
@alexey-milovidov alexey-milovidov removed the close in a month if not active This will be closed in case of no information label May 7, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is overengineered, and we will have trouble renaming/removing various options for AZ-detection (I'd prefer it to be a single option, and possibly just take it from an explicit value in a config). However, this PR is acceptable - we can deal with it.

@alexey-milovidov alexey-milovidov self-assigned this May 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 7, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Also, it creates a tech debt with Kafka2.

@ilejn

ilejn commented May 7, 2026

Copy link
Copy Markdown
Contributor Author

Also, it creates a tech debt with Kafka2.

Alexey, could you explain, please.

The only relation with Kafka2 that came to my mind is Kafka2 should be covered by tests. And it is covered.

Merged via the queue into ClickHouse:master with commit f9c34bf May 7, 2026
165 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label May 7, 2026
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Jun 17, 2026
Issue ClickHouse#81402 reported that availability-zone detection failed on EC2
instances configured for "IMDSv2 only (token required)", because
`getAvailabilityZoneOrException` issued a plain unauthenticated `GET`
against the instance metadata service, which such instances reject with
`401 Unauthorized`.

The behavior was fixed in master by ClickHouse#81323 (`kafka_aws_az_aware`), which
makes `getAvailabilityZoneOrException` acquire an IMDSv2 session token via
`PUT /latest/api/token` and send it with the availability-zone `GET`,
falling back to the token-less IMDSv1 request when the metadata service
does not implement the token endpoint. That change did not add a test
covering the IMDSv2-only scenario in `test_placement_info`.

This adds that missing coverage: a new mock metadata server
`imdsv2_server.py` that issues tokens on `PUT /latest/api/token` and
rejects `GET` requests without a valid `x-aws-ec2-metadata-token` header
(`401`), plus a `node_imds_v2` instance and a
`test_placement_info_from_imdsv2_only` case that asserts the availability
zone is still loaded against such an endpoint.

The test originates from ClickHouse#103549, which proposed an equivalent fix before
ClickHouse#81323 was merged; that pull request is now superseded for the production
change, so only its regression test is kept here.

Co-Authored-By: ashrithb <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants