DZone: Programming & DevOps news, tutorials & toolsProgramming, Web Development, and DevOps news, tutorials and tools for beginners to experts. Hundreds of free publications, over 1M members, totally free.DZone: Programming & DevOps news, tutorials & tools Thanks for visiting DZone today, Edit Profile Manage Email Subscriptions How to Post to DZone Article Submission Guidelines Sign Out View Profile Post Post an Article Manage My Drafts Over 2 million developers have joined DZone. Log In / Join Search Please enter at least three characters to search No search results View All Results Refcards Trend Reports Events Video Library Refcards Trend Reports Events View Events Video Library DZone Spotlight Monday, September 16 View All Articles » 10 Things To Avoid in Domain-Driven Design (DDD) By Reza Ganji CORE Domain-Driven Design (DDD) is an important strategic approach to software development. It involves deeply understanding and modeling a business domain, particularly beneficial in complex domains with intricate business rules, processes, and interactions. However, effectively implementing DDD requires discipline, a strong grasp of the domain, and the avoidance of common pitfalls that can lead to suboptimal designs and technical debt. In this article, we'll explore 10 things to avoid in DDD and examples to illustrate these pitfalls. 1. Focusing Too Much on Technical Patterns Sample Scenario A team begins a project by excessively creating repositories, aggregates, and value objects without fully grasping the business domain. For example, they develop a complicated repository for managing Customer entities without understanding how customers are represented and utilized within the business. Consequently, the repository contains numerous unnecessary methods that do not align with the domain's actual use cases and requirements. Avoidance Tip DDD's main focus should be comprehending the domain. This involves a collaborative effort, with the team working closely with domain experts to establish a shared understanding and a common language that accurately represents the fundamental business concepts. Technical patterns like repositories and aggregates should naturally emerge from the domain model, rather than being prematurely implemented or excessively emphasized at the beginning. 2. Over-Engineering the Model Sample Scenario A team strictly adheres to DDD principles by creating a detailed domain model that includes separate classes for every conceivable domain concept. For instance, they create individual classes for CustomerName, CustomerEmail, and CustomerAddress when these could have been combined into a more straightforward Customer value object. The resulting model becomes overly complex and difficult to maintain, with little added value. Avoidance Tip To prevent potential issues, it is your responsibility to maintain a domain model that is uncomplicated and accurately reflects the domain. This diligent approach is important to focus on modeling the components of the domain that offer strategic importance and to streamline or exclude less critical elements. Remember, Domain-Driven Design (DDD) is primarily concerned with strategic design and not with needlessly complexifying the domain model with unnecessary intricacies. 3. Ignoring the Ubiquitous Language Sample Scenario In a collaborative environment, it's common for developers and domain experts to employ distinct technical vocabulary. For instance, while domain experts commonly use the term "Purchase Orders," developers might utilize OrderEntity within their codebase. This terminology disparity can lead to various challenges, including misunderstandings, mishandled implementations, and a need for synchronization between the code and the specific business requirements. Such discrepancies can impede effective communication and hinder the accurate translation of business logic into technical implementations. Therefore, ensuring a shared understanding of terminology between developers and domain experts is crucial for fostering effective collaboration and aligning technical solutions with business needs. Avoidance Tip Establishing and upholding a universal language is important to ensure clear communication and understanding across all aspects of the project. This process involves close collaboration with domain experts to develop and maintain a consistent vocabulary. The language should be applied uniformly in code, documentation, conversations, and all forms of communication. By doing so, we can prevent misunderstandings and guarantee that the model accurately reflects the business requirements. This approach fosters alignment between all stakeholders and promotes cohesion throughout the project lifecycle. 4. Misunderstanding Bounded Contexts Sample Scenario When a team tries to utilize a single "Customer" entity across various subdomains like "Billing," "Customer Service," and "Marketing," it leads to ambiguity and unwarranted interconnections between different sections of the application. For instance, modifications made to the "Customer" entity within the "Billing" context can unintentionally impact the "Marketing" context, resulting in unforeseen behavior and data discrepancies. Avoidance Tip When defining bounded contexts, clearly delineating different areas of the domain with distinct responsibilities is crucial. Each bounded context should possess its own model and clearly defined boundaries. To maintain the integrity of each context's model, it's essential to facilitate integration between contexts through well-defined interfaces or anti-corruption layers. These measures ensure that the responsibilities and integrity of each bounded context are preserved. 5. Not Aligning With Business Strategy Sample Scenario The team's approach to Domain-Driven Design (DDD) is purely technical, focusing on modeling all aspects of the domain without considering the business strategy. Their extensive efforts have been invested in modeling peripheral elements of the domain, such as "Employee Attendance" and "Office Supplies Management," while overlooking the core business process that provides the most value: "Order Fulfillment." As a result of this approach, the resulting model is complex but needs to align with the business's strategic goals. Avoidance Tip It's crucial to leverage Domain-Driven Design (DDD) to deeply analyze and concentrate on the domain's most vital and influential parts. Identify the aspects that deliver the highest value to the business and ensure that your modeling efforts are closely aligned with the business's overarching priorities and strategic objectives. Actively collaborating with key business stakeholders is essential to gain a comprehensive understanding of what holds the greatest value to them and subsequently prioritize these areas in your modeling endeavors. This approach will optimally reflect the business's critical needs and contribute to the successful realization of strategic goals. 6. Overusing Entities Instead of Value Objects Sample Scenario Many software developers conceptualize "Currency" as an entity with a unique identifier, essentially treating it as a standalone object. However, it could be more efficient to view "Currency" as a value object defined by its attributes, such as "USD" or "EUR." By persisting with the former approach, the team inadvertently introduces unnecessary complexity, such as the need to manage the lifecycle, state, and identity of "Currency" entities. This unnecessarily complicates the codebase, making it more cumbersome and adding to its bloat. Avoidance Tip When designing your software, it is beneficial to utilize value objects as much as possible, especially for types and objects that remain unchanged and do not require a unique identity. Value objects are advantageous as they are more straightforward to manage and predictable, often leading to more maintainable code. These objects can effectively represent domain-specific values such as dates, monetary values, measurements, and other essential concepts. 7. Neglecting Aggregates and Their Boundaries Sample Scenario Aggregates represent clusters or groups of related objects treated as a single unit for data changes in the context of domain-driven design. When a team models a "Product" as a standalone entity, they may overlook its aggregate boundaries, allowing multiple services to modify it independently. This can lead to conflicting updates by different services to the same "Product," resulting in inconsistent data and business rule violations. Defining and respecting aggregate boundaries is crucial for maintaining data integrity and ensuring consistency across different system parts. Avoidance Tip Aggregates are an essential concept in domain-driven design (DDD) that involves a cluster of related objects treated as a unit for data changes. An aggregate comprises one specific object, known as the aggregate root, which serves as the entry point for all modifications within the aggregate. Encapsulating related objects within an aggregate and making modifications through the aggregate root makes it easier to enforce business rules and maintain data consistency and integrity. This approach helps to ensure that all operations and changes occur within the defined boundaries of the aggregate, allowing for better control and management of complex data structures. 8. Failing To Use Domain Events Effectively Sample Scenario One team ignores domain events and directly invokes services. This causes their system to become tightly coupled, increasing dependencies between different system parts. As a result, the system becomes more challenging to modify or extend because any change in one service directly impacts other services, leading to a domino effect of changes and making the system more fragile. On the other hand, in a different scenario, another team overuses domain events by emitting an event for every minor change, such as "CustomerCreated," "CustomerUpdated," and "CustomerDeleted," even when other parts of the system don't need these events. This results in excessive events being generated and processed, causing performance degradation, increased complexity, and unnecessary resource consumption. The system becomes cluttered with events that serve no real purpose, leading to event fatigue and making it harder to identify and respond to critical events. Avoidance Tip When developing your system, it is essential to utilize domain events to capture significant changes within the domain. These events should be meticulously designed to serve a clear purpose and communicate meaningful state changes within the system. By employing domain events, you can effectively decouple various parts of the system, thus facilitating scalability and improved maintainability. However, exercising caution and avoiding overusing domain events is crucial, as doing so may lead to unnecessary complexity and potential performance issues. It is essential to strike a balance and only employ genuinely beneficial domain events rather than indiscriminately incorporating them throughout the system. This approach will ultimately contribute to a more streamlined and manageable system architecture. 9. Ignoring the Importance of Collaboration With Domain Experts Sample Scenario The development team embarked on creating a "Loan Approval" process without soliciting insights from loan officers or other experts in the field. Consequently, the model omitted critical business rules, including specific risk assessment criteria, verification steps, and regulatory requirements. This significant oversight resulted in a software solution that needed to align with business needs, leading to its rejection by stakeholders. Avoidance Tip It's crucial to establish close collaboration with domain experts at every stage of the design and development process. It's important to regularly engage with them to confirm that your understanding of the domain is accurate. You can involve domain experts in discussions, design sessions, and model reviews to gather their valuable insights. Techniques such as Event Storming and Domain Storytelling can facilitate collaborative modeling, ensuring that the model faithfully represents the domain. 10. Treating DDD as a Silver Bullet Sample Scenario The team in question mistakenly believes that Domain-Driven Design (DDD) is universally applicable to all software projects, regardless of the domain's complexity. This leads them to apply DDD principles to a simple CRUD application, such as a 'To-Do List' or 'Contact Management' system. The result is a needlessly complex codebase that is difficult to maintain and incurs high development costs, far exceeding the project's needs. Avoidance Tip Domain-driven design (DDD) is most suitable for domains known for their complexity, particularly those characterized by intricate business rules and processes. In such complex domains, a close alignment between business and technical teams is crucial for success. In contrast, DDD may not be the best fit for simple applications or domains where a more straightforward approach would suffice. It's important to carefully assess the domain's complexity and the project's specific requirements to determine the most appropriate approach. Conclusion Domain-driven design is a powerful methodology for building software that is aligned with complex business domains. However, like any powerful tool, it must be used wisely. By avoiding these ten common pitfalls, you can leverage DDD to its fullest potential, creating software that accurately reflects and supports your business goals. Remember that DDD is not just about patterns and practices; it is about fostering collaboration, creating a shared understanding of the domain, and building solutions that provide real strategic value, a value that your collaborative efforts can significantly contribute to. By focusing on understanding the domain, avoiding over-engineering, aligning with business strategy, and maintaining clear, consistent language, teams can create models that are not only technically sound but also deeply aligned with the business's needs. More Understanding Floating-Point Precision Issues in Java By Dmitry Egorov CORE Java Floating Numbers Look Familiar In Java, we have two types of floating-point numbers: float and double. All Java developers know them but can't answer a simple question described in the following meme: Are you robot enough? What Do You Already Know about Float and Double? float and double represent floating-point numbers. float uses 32 bits, while double uses 64 bits, which can be utilized for the decimal or fractional part. But what does that actually mean? To understand, let's review the following examples: Intuitive results are completely contradictory and seem to contain mistakes: But how is this possible? Where do the 4 and 2 at the end of the numbers come from? To understand, let's review how these numbers are actually created. Don’t Trust Your Eyes: Reviewing How 0.1 Converted to IEEE Standard float and double follow the IEEE standard, which defines how to use 32/64 bits to represent a floating-point number. But how is a number like 0.1 converted to a bit array? Without diving too much into the details, the logic is similar to the following: Converting Floating 0.1 to Arrays of Bits First In the first stage, we need to convert the decimal representation of 0.1 to binary using the following steps: Multiply 0.1 by 2 and write down the decimal part. Take the fractional part, multiply it by 2, and note the decimal part. Repeat the first step with the fraction from the second step. So for 0.1, we get the following results: Step Operation Integer Part Fraction 1 0.1 * 2 0 0.2 2 0.2 * 2 0 0.4 3 0.4 * 2 0 0.8 4 0.8 * 2 1 0.6 5 0.6 * 2 1 0.2 6 0.2 * 2 0 0.4 After repeating these steps, we get a binary sequence like 0.0001100110011 (in fact, it’s a repeating infinite sequence). Converting Binary Array to IEEE Standard Inside float/double, we don't keep the binary array as it is. float/double follow the IEEE 754 standard. This standard splits the number into three parts: Sign (0 for positive and 1 for negative) Exponent (defines the position of the floating point, with an offset of 127 for float or 1023 for double) Mantissa (the part that comes after the floating point, but is limited by the number of remaining bits) So now converting 0.0001100110011... to IEEE, we get: Sign 0 for positive Exponent : Considering first four zeros 0.0001100110011 = -4 + 127 = 123 (or 01111011) Mantissa 1100110011 (Mantissa ignores first 1), so we get 100110011 So the final representation is: So What? How Do These Numbers Explain Weird Results? After all these conversions, we lose precision due to two factors: We lose precision when converting from the infinite binary representation (which has repeating values like 1100110011). We lose precision when converting to IEEE format because we consider only the first 32 or 64 bits. This means that the value we have in float or double doesn't represent exactly 0.1. If we convert the IEEE bit array from float to a "real float," we get a different value. More precisely, instead of 0.1, we get 0.100000001490116119384765625. How can we verify this? There are a couple of ways. Take a look at the following code: And as we expect, we get the following results: But if we want to go deeper, we can write reverse engineering code: As expected, it confirms our ideas: Answering the Question and Drawing Conclusions Now that we know the value we see at initialization is different from what is actually stored in float/double, we expect the value on the left (0.1) but instead, we initialize with the value on the right (0.100000001490116119384765625): So, knowing this, it's clear that when we perform actions such as adding or multiplying values, this difference becomes more pronounced, until it becomes visible during printing. Conclusions Here are the conclusions we can draw: Don’t use floating-point values for precise calculations, such as in finance, medicine, or complex science. Don’t compare two double values for equality directly; instead, check the difference between them with a small delta. For example: boolean isEqual = Math.abs(a - b) < 0.0000001; Use BigDecimal or similar classes for precise calculations. I hope you now understand why 0.1 + 0.2 returns 0.300000000000004. Thanks for reading! More Trend Report Enterprise Security Security is everywhere: Behind every highly performant application, or even detected threat, there is a powerful security system and set of processes implemented. And in the off chance there are NOT such systems in place, that fact will quickly make itself known. We are living in an entirely new world, where bad actors are growing more and more sophisticated the moment we make ourselves "comfortable." So how do you remain hypervigilant in this ever so treacherous environment?DZone's annual Enterprise Security Trend Report has you covered. The research and expert articles explore the fastest emerging techniques and nuances in the security space, diving into key topics like CSPM, full-stack security practices and challenges, SBOMs and DevSecOps for secure software supply chains, threat hunting, secrets management, zero-trust security, and more. It's time to expand your organization's tactics and put any future attackers in their place as you hear from industry leaders and experts on how they are facing these challenges in everyday scenarios — because if there is one thing we know about the cyberspace, any vulnerabilities left to chance will always be exposed. Download Refcard #398 Open-Source Data Management Practices and Patterns By Abhishek Gupta CORE Download Refcard #370 Data Orchestration on Cloud Essentials By Sudip Sengupta CORE Download More Articles DZone Annual Community Survey: What's in Your 2024 Tech Stack? Are you a software developer or other tech professional? If you’re reading this, chances are pretty good that the answer is "yes." Long story short — we want DZone to work for you! We're asking that you take our annual community survey so we can better serve you! ^^ You can also enter the drawing for a chance to receive an exclusive DZone Swag Pack! The software development world moves fast, and we want to keep up! Across our community, we found that readers come to DZone for various reasons, including to learn about new development trends and technologies, find answers to help solve problems they have, connect with other peers, publish their content, and expand their personal brand's audience. In order to continue helping the DZone Community reach goals such as these, we need to know more about you, your learning preferences, and your overall experience on dzone.com and with the DZone team. For this year's DZone Community research, our primary goals are to: Learn about developer tech preferences and habits Identify content types and topics that developers want to get more information on Share this data for public consumption! To support our Community research, we're focusing on several primary areas in the survey: You, including your experience, the types of software you work on, and the tools you use How you prefer to learn and what you want to learn more about on dzone.com The ways in which you engage with DZone, your content likes vs. dislikes, and your overall journey on dzone.com As a community-driven site, our relationships with our members and contributors is invaluable, and we want to make sure that we continue to serve our audience to the best of our ability. If you're curious to see the report from the 2023 Community survey, feel free to check it out here! Thank you in advance for your participation!—Your favorite DZone Content and Community team By Dominique Roller Optimizing Container Synchronization for Frequent Writes Efficient data synchronization is crucial in high-performance computing and multi-threaded applications. This article explores an optimization technique for scenarios where frequent writes to a container occur in a multi-threaded environment. We’ll examine the challenges of traditional synchronization methods and present an advanced approach that significantly improves performance for write-heavy environments. The method in question is beneficial because it is easy to implement and versatile, unlike pre-optimized containers that may be platform-specific, require special data types, or bring additional library dependencies. Traditional Approaches and Their Limitations Imagine a scenario where we have a cache of user transactions: C++ struct TransactionData { long transactionId; long userId; unsigned long date; double amount; int type; std::string description; }; std::map> transactionCache; // key - userId In a multi-threaded environment, we need to synchronize access to this cache. The traditional approach might involve using a mutex: C++ class SimpleSynchronizedCache { public: void write(const TransactionData&& transaction) { std::lock_guard lock(cacheMutex); transactionCache[transaction.userId].push_back(transaction); } std::vector read(const long&& userId) { std::lock_guard lock(cacheMutex); try { return transactionCache.at(userId); } catch (const std::out_of_range& ex) { return std::vector(); } } std::vector pop(const long& userId) { std::lock_guard lock(_cacheMutex); auto userNode = _transactionCache.extract(userId); return userNode.empty() ? std::vector() : std::move(userNode.mapped()); } private: std::map> transactionCache; std::mutex cacheMutex; }; As system load increases, especially with frequent reads, we might consider using a shared_mutex: C++ class CacheWithSharedMutex { public: void write(const TransactionData&& transaction) { std::lock_guard lock(cacheMutex); transactionCache[transaction.userId].push_back(transaction); } std::vector read(const long&& userId) { std::shared_lock lock(cacheMutex); try { return transactionCache.at(userId); } catch (const std::out_of_range& ex) { return std::vector(); } } std::vector pop(const long& userId) { std::lock_guard lock(_cacheMutex); auto userNode = _transactionCache.extract(userId); return userNode.empty() ? std::vector() : std::move(userNode.mapped()); } private: std::map> transactionCache; std::shared_mutex cacheMutex; }; However, when the load is primarily generated by writes rather than reads, the advantage of a shared_mutex over a regular mutex becomes minimal. The lock will often be acquired exclusively, negating the benefits of shared access. Moreover, let’s imagine that we don’t use read() at all — instead, we frequently write incoming transactions and periodically flush the accumulated transaction vectors using pop(). As pop() involves reading with extraction, both write() and pop() operations would modify the cache, necessitating exclusive access rather than shared access. Thus, the shared_lock becomes entirely useless in terms of optimization over a regular mutex, and maybe even performs worse — its more intricate implementation is now used for the same exclusive locks that a faster regular mutex provides. Clearly, we need something else. Optimizing Synchronization With the Sharding Approach Given the following conditions: A multi-threaded environment with a shared container Frequent modification of the container from different threads Objects in the container can be divided for parallel processing by some member variable. Regarding point 3, in our cache, transactions from different users can be processed independently. While creating a mutex for each user might seem ideal, it would lead to excessive overhead in maintaining so many locks. Instead, we can divide our cache into a fixed number of chunks based on the user ID, in a process known as sharding. This approach reduces the overhead and yet allows the parallel processing, thereby optimizing performance in a multi-threaded environment. C++ class ShardedCache { public: ShardedCache(size_t shardSize): _shardSize(shardSize), _transactionCaches(shardSize) { std::generate( _transactionCaches.begin(), _transactionCaches.end(), []() { return std::make_unique(); }); } void write(const TransactionData& transaction) { _transactionCaches[transaction.userId % _shardSize]->write(transaction); } std::vector read(const long& userId) { _transactionCaches[userId % _shardSize]->read(userId); } std::vector pop(const long& userId) { return std::move(_transactionCaches[userId % _shardSize]->pop(userId)); } private: const size_t _shardSize; std::vector> _transactionCaches; }; This approach allows for finer-grained locking without the overhead of maintaining an excessive number of mutexes. The division can be adjusted based on system architecture specifics, such as size of a thread pool that works with the cache, or hardware concurrency. Let’s run tests where we check how sharding accelerates cache performance by testing different partition sizes. Performance Comparison In these tests, we aim to do more than just measure the maximum number of operations the processor can handle. We want to observe how the cache behaves under conditions that closely resemble real-world scenarios, where transactions occur randomly. Our optimization goal is to minimize the processing time for these transactions, which enhances system responsiveness in practical applications. The implementation and tests are available in the GitHub repository. C++ #include #include #include #include #include #include #include #include #include "SynchronizedContainers.h" const auto hardware_concurrency = (size_t)std::thread::hardware_concurrency(); class TaskPool { public: template TaskPool(size_t poolSize, Callable task) { for (auto i = 0; i < poolSize; ++i) { _workers.emplace_back(task); } } ~TaskPool() { for (auto& worker : _workers) { if (worker.joinable()) worker.join(); } } private: std::vector _workers; }; template class Test { public: template Test(const int testrunsNum, const size_t writeWorkersNum, const size_t popWorkersNum, const std::string& resultsFile, CacheArgs&& ... cacheArgs) : _cache(std::forward(cacheArgs)...), _writeWorkersNum(writeWorkersNum), _popWorkersNum(popWorkersNum), _resultsFile(resultsFile), _testrunsNum(testrunsNum), _testStarted (false) { std::random_device rd; _randomGenerator = std::mt19937(rd()); } void run() { for (auto i = 0; i < _testrunsNum; ++i) { runSingleTest(); logResults(); } } private: void runSingleTest() { { std::lock_guard lock(_testStartSync); _testStarted = false; } // these pools won’t just fire as many operations as they can, // but will emulate real-time occuring requests to the cache in multithreaded environment auto writeTestPool = TaskPool(_writeWorkersNum, std::bind(&Test::writeTransactions, this)); auto popTestPool = TaskPool(_popWorkersNum, std::bind(&Test::popTransactions, this)); _writeTime = 0; _writeOpNum = 0; _popTime = 0; _popOpNum = 0; { std::lock_guard lock(_testStartSync); _testStarted = true; _testStartCv.notify_all(); } } void logResults() { std::cout << "===============================================" << std::endl; std::cout << "Writing operations number per sec:\t" << _writeOpNum / 60. << std::endl; std::cout << "Writing operations avg time (mcsec):\t" << (double)_writeTime / _writeOpNum << std::endl; std::cout << "Pop operations number per sec: \t" << _popOpNum / 60. << std::endl; std::cout << "Pop operations avg time (mcsec): \t" << (double)_popTime / _popOpNum << std::endl; std::ofstream resultsFilestream; resultsFilestream.open(_resultsFile, std::ios_base::app); resultsFilestream << _writeOpNum / 60. << "," << (double)_writeTime / _writeOpNum << "," << _popOpNum / 60. << "," << (double)_popTime / _popOpNum << std::endl; std::cout << "Results saved to file " << _resultsFile << std::endl; } void writeTransactions() { { std::unique_lock lock(_testStartSync); _testStartCv.wait(lock, [this] { return _testStarted; }); } std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); // hypothetical system has around 100k currently active users std::uniform_int_distribution<> userDistribution(1, 100000); // delay up to 5 ms for every thread not to start simultaneously std::uniform_int_distribution<> waitTimeDistribution(0, 5000); std::this_thread::sleep_for(std::chrono::microseconds(waitTimeDistribution(_randomGenerator))); for ( auto iterationStart = std::chrono::steady_clock::now(); iterationStart - start < std::chrono::minutes(1); iterationStart = std::chrono::steady_clock::now()) { auto generatedUser = userDistribution(_randomGenerator); TransactionData dummyTransaction = { 5477311, generatedUser, 1824507435, 8055.05, 0, "regular transaction by " + std::to_string(generatedUser)}; std::chrono::steady_clock::time_point operationStart = std::chrono::steady_clock::now(); _cache.write(dummyTransaction); std::chrono::steady_clock::time_point operationEnd = std::chrono::steady_clock::now(); ++_writeOpNum; _writeTime += std::chrono::duration_cast(operationEnd - operationStart).count(); // make span between iterations at least 5ms std::this_thread::sleep_for(iterationStart + std::chrono::milliseconds(5) - std::chrono::steady_clock::now()); } } void popTransactions() { { std::unique_lock lock(_testStartSync); _testStartCv.wait(lock, [this] { return _testStarted; }); } std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); // hypothetical system has around 100k currently active users std::uniform_int_distribution<> userDistribution(1, 100000); // delay up to 100 ms for every thread not to start simultaneously std::uniform_int_distribution<> waitTimeDistribution(0, 100000); std::this_thread::sleep_for(std::chrono::microseconds(waitTimeDistribution(_randomGenerator))); for ( auto iterationStart = std::chrono::steady_clock::now(); iterationStart - start < std::chrono::minutes(1); iterationStart = std::chrono::steady_clock::now()) { auto requestedUser = userDistribution(_randomGenerator); std::chrono::steady_clock::time_point operationStart = std::chrono::steady_clock::now(); auto userTransactions = _cache.pop(requestedUser); std::chrono::steady_clock::time_point operationEnd = std::chrono::steady_clock::now(); ++_popOpNum; _popTime += std::chrono::duration_cast(operationEnd - operationStart).count(); // make span between iterations at least 100ms std::this_thread::sleep_for(iterationStart + std::chrono::milliseconds(100) - std::chrono::steady_clock::now()); } } CacheImpl _cache; std::atomic _writeTime; std::atomic _writeOpNum; std::atomic _popTime; std::atomic _popOpNum; size_t _writeWorkersNum; size_t _popWorkersNum; std::string _resultsFile; int _testrunsNum; bool _testStarted; std::mutex _testStartSync; std::condition_variable _testStartCv; std::mt19937 _randomGenerator; }; void testCaches(const size_t testedShardSize, const size_t workersNum) { if (testedShardSize == 1) { auto simpleImplTest = Test( 10, workersNum, workersNum, "simple_cache_tests(" + std::to_string(workersNum) + "_workers).csv"); simpleImplTest.run(); } else { auto shardedImpl4Test = Test( 10, workersNum, workersNum, "sharded_cache_" + std::to_string(testedShardSize) + "_tests(" + std::to_string(workersNum) + "_workers).csv", 4); shardedImpl4Test.run(); } } int main() { std::cout << "Hardware concurrency: " << hardware_concurrency << std::endl; std::array testPlan = { 1, 4, 8, 32, 128, 4096, 100000 }; for (auto i = 0; i < testPlan.size(); ++i) { testCaches(testPlan[i], 4 * hardware_concurrency); } // additional tests with diminished load to show limits of optimization advantage std::array additionalTestPlan = { 1, 8, 128, 100000 }; for (auto i = 0; i < additionalTestPlan.size(); ++i) { testCaches(additionalTestPlan[i], hardware_concurrency); } } We observe that with 2,000 writes and 300 pops per second (with a concurrency of 8) — which are not very high numbers for a high-load system — optimization using sharding significantly accelerates cache performance, by orders of magnitude. However, evaluating the significance of this difference is left to the reader, as, in both scenarios, operations took less than a millisecond. It’s important to note that the tests used a relatively lightweight data structure for transactions, and synchronization was applied only to the container itself. In real-world scenarios, data is often more complex and larger, and synchronized processing may require additional computations and access to other data, which can significantly increase the time of operation itself. Therefore, we aim to spend as little time on synchronization as possible. The tests do not show the significant difference in processing time when increasing the shard size. The greater the size the bigger is the maintaining overhead, so how low should we go? I suspect that the minimal effective value is tied to the system's concurrency, so for modern server machines with much greater concurrency than my home PC, a shard size that is too small won’t yield the most optimal results. I would love to see the results on other machines with different concurrency that may confirm or disprove this hypothesis, but for now I assume it is optimal to use a shard size that is several times larger than the concurrency. You can also note that the largest size tested — 100,000 — effectively matches the mentioned earlier approach of assigning a mutex to each user (in the tests, user IDs were generated within the range of 100,000). As can be seen, this did not provide any advantage in processing speed, and this approach is obviously more demanding in terms of memory. Limitations and Considerations So, we determined an optimal shard size, but this is not the only thing that should be considered for the best results. It’s important to remember that such a difference compared to a simple implementation exists only because we are attempting to perform a sufficiently large number of transactions at the same time, causing a “queue” to build up. If the system’s concurrency and the speed of each operation (within the mutex lock) allow operations to be processed without bottlenecks, the effectiveness of sharding optimization decreases. To demonstrate this, let’s look at the test results with reduced load — at 500 writes and 75 pops (with a concurrency of 8) — the difference is still present, but it is no longer as significant. This is yet another reminder that premature optimizations can complicate code without significantly impacting results. It’s crucial to understand the application requirements and expected load. Also, it’s important to note that the effectiveness of sharding heavily depends on the distribution of values of the chosen key (in this case, user ID). If the distribution becomes heavily skewed, we may revert to performance more similar to that of a single mutex — imagine all of the transactions coming from a single user. Conclusion In scenarios with frequent writes to a container in a multi-threaded environment, traditional synchronization methods can become a bottleneck. By leveraging the ability of parallel processing of data and predictable distribution by some specific key and implementing a sharded synchronization approach, we can significantly improve performance without sacrificing thread safety. This technique can prove itself effective for systems dealing with user-specific data, such as transaction processing systems, user session caches, or any scenario where data can be logically partitioned based on a key attribute. As with any optimization, it’s crucial to profile your specific use case and adjust the implementation accordingly. The approach presented here provides a starting point for tackling synchronization challenges in write-heavy, multi-threaded applications. Remember, the goal of optimization is not just to make things faster, but to make them more efficient and scalable. By thinking critically about your data access patterns and leveraging the inherent structure of your data, you can often find innovative solutions to performance bottlenecks. By Alexander Iskhakov Designing a Secure Architecture for Distributed Systems Securing distributed systems is a complex challenge due to the diversity and scale of components involved. With multiple services interacting across potentially unsecured networks, the risk of unauthorized access and data breaches increases significantly. This article explores a practical approach to securing distributed systems using an open-source project. The project demonstrates how to integrate several security mechanisms and technologies to tackle common security challenges such as authentication, authorization, and secure communication. Understanding Security Challenges in Distributed Systems Distributed systems involve multiple services or microservices that must communicate securely across a network. Key security challenges in such architectures include: Secure communication: Ensuring that data transmitted between services is encrypted and safe from eavesdropping or tampering Authentication: Verifying the identities of users and services to prevent unauthorized access Authorization: Controlling what authenticated users and services are allowed to do, based on their roles and permissions Policy enforcement: Implementing fine-grained access controls and policies that govern service-to-service and user interactions Certificate management: Managing digital certificates for encrypting data and establishing trust between services This open-source project addresses these challenges using several integrated technologies and solutions. Project Setup and Configuration The project begins with setting up a secure environment using shell scripts and Docker. The setup involves provisioning digital certificates and starting the necessary services to ensure all components are ready for secure communication. Steps to Set Up the Environment 1. Provisioning Certificates The project uses a shell script (provisioning.sh) to simulate a Certificate Authority (CA) and generate the necessary certificates for the services. ./provisioning.sh 2. Launching Services Docker Compose is used to start all services defined in the project, ensuring they are configured correctly for secure operation. docker-compose up 3. Testing Service-to-Service Communication To validate service-to-service communication using certificates and JWT tokens, the test_services.sh script is provided. This script demonstrates how different services interact securely using their assigned certificates. Solving Security Challenges in Distributed Systems The project integrates several key technologies to address the primary security challenges mentioned earlier. Here's how each challenge is tackled: 1. Secure Communication With Mutual TLS (mTLS) Challenge In a distributed system, services must communicate securely to prevent unauthorized access and data breaches. Solution The project uses Mutual TLS (mTLS) to secure communication between services. mTLS ensures that both the client and server authenticate each other using their respective certificates. This mutual authentication prevents unauthorized services from communicating with legitimate services. Implementation Nginx is configured as a reverse proxy to handle mTLS. It requires both client and server certificates for establishing a secure connection, ensuring that data transmitted between services remains confidential and tamper-proof. 2. Authentication With Keycloak Challenge Properly authenticating users and services is critical to prevent unauthorized access. Solution The project leverages Keycloak, an open-source identity and access management solution, to manage authentication. Keycloak supports multiple authentication methods, including OpenID Connect and client credentials, making it suitable for both user and service authentication. User Authentication: Users are authenticated using OpenID Connect. Keycloak is configured with a client (appTest-login-client) that handles user authentication flows, including login, token issuance, and callback handling. Service Authentication: For service-to-service authentication, the project uses a Keycloak client (client_credentials-test) configured for the client credentials grant type. This method is ideal for authenticating services without user intervention. Authentication Flow Example Users navigate to the login page. After successful login, Keycloak redirects the user to a callback page with an authorization code. The authorization code is then exchanged for a JWT token, which is used for subsequent requests. The authn.js file in the nginx/njs directory provides a detailed implementation of this flow. Service Authentication Example Using Client Credentials curl -X POST "http://localhost:9000/realms/tenantA/protocol/openid-connect/token" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=client_credentials" \ -d "client_id=client_credentials-test" \ -d "client_secret=your-client-secret-here" 3. User Authorization With Open Policy Agent (OPA) and JWT Challenge Enforcing fine-grained access controls to ensure that authenticated users and services only have access to authorized resources Solution The project utilizes a combination of Open Policy Agent (OPA) and JWT tokens to enforce authorization policies. The project demostrate three different strategies for JWT validation to ensure robust security: Retrieving certificates from Keycloak: Fetches the certificates dynamically from Keycloak to validate the token. Using x5t (Thumbprint): Uses the thumbprint embedded in the token to retrieve the public key from a local trust store. Embedded certificate validation: Validates the token using an embedded certificate, ensuring the certificate is validated against a trusted Certificate Authority (CA). Refer to the nginx/njs/token.js file for the detailed implementation of these strategies. 4. Policy Enforcement With Open Policy Agent (OPA) Challenge Implementing dynamic and flexible access control policies for both services and users Solution OPA is used to enforce fine-grained policies for access control. Policies are written in a declarative language (Rego) and stored in the opa/ directory. These policies dictate the conditions under which services can communicate and users can access resources, ensuring that access controls are consistently applied across the system. 5. Certificate Management Challenge Managing digital certificates for services to establish trust and secure communications Solution: The project includes a robust certificate management system. A shell script (provisioning.sh) is used to simulate a Certificate Authority (CA) and generate certificates for each service. This approach simplifies certificate management and ensures that all services have the necessary credentials for secure communication. We also added an endpoint to update the service certificate without the need of nginx restart. curl --insecure https://localhost/certs --cert certificates/gen/serviceA/client.crt --key certificates/gen/serviceA/client.key -F cert=@certificates/gen/serviceA/client.crt -F key=@certificates/gen/serviceA/client.key Conclusion Building a secure distributed system requires careful consideration of various security aspects, including secure communication, authentication, authorization, policy enforcement, and certificate management. This open-source project provides a comprehensive example of how to integrate multiple security mechanisms to address these challenges effectively. By following the setup and configurations demonstrated in this project, developers can leverage mutual TLS, Keycloak, Open Policy Agent, and Nginx to build a robust security architecture. These technologies, when combined, provide a strong foundation for securing distributed systems against a wide range of threats, ensuring both data protection and secure access control. By Alexsandro Souza How Stalactite ORM Implements Its Fluent DSL “DX”, aka Developer Experience One of the goals of Stalactite is to make developers aware of the impact of the mapping of their entities onto the database, and, as a consequence, onto performances. To fulfill this goal, the developer's experience, as a user of the Mapping API, is key to helping him express his intention. The idea is to guide the user-developer in the choices he can make while he describes its persistence. As you may already know, Stalactite doesn’t use annotation or XML files for that. It proposes a fluent API that constrains user choices according to the context. To clarify: available methods after a call to mapOneToOne(..) are not the same as the ones after mapOneToMany(..). This capacity can be done in different ways. Stalactite chose to leverage Java proxies for it and combines it with the multiple-inheritance capability of interfaces. Contextualized Options Let’s start with a simple goal: we want to help a developer express the option of aliasing a column in a request, and also the option of casting it. Usually, we would find something like: Java select() .add("id", new ColumnOptions().as("countryId").cast("int")) .from(..); It would be smarter to have this: Java select() .add("id").as("countryId").cast("int") .add("name").as("countryName") .add("population").cast("long") .from(..); As the former is kind of trivial to implement and many examples can be found on the Internet, in particular Spring with its Security DSL or its MockMVC DSL, the latter is trickier because we have to locally mix the main API (select().from(..).where(..)) with some local one (as(..).cast(..)) on the return type of the add(..) method. This means that if the main API is brought by the FluentSelect interface, and the column options by the FluentColumnOptions interface, the method add(String) must return a third one that inherits from both: the FluentSelectColumnOptions interface. Java /** The main API */ interface FluentSelect { FluentSelect add(String columnName); FluentFrom from(String tableName); } /** The column options API */ interface FluentColumnOptions { FluentColumnOptions as(String alias); FluentColumnOptions cast(String alias); } /** The main API with column options as an argument to make it more fluent */ interface EnhancedFluentSelect extends FluentSelect { /** The returned type of this method is overwritten to return and enhanced version */ FluentSelectColumnOptions add(String columnName); FluentFrom from(String tableName); } /** The mashup between main API and column options API */ interface FluentSelectColumnOptions extends EnhancedFluentSelect, // we inherit from it to be capable of coming back to from(..) or chain with another add(..) FluentColumnOptions { /** we overwrite return types to make it capable of chaining with itself */ FluentSelectColumnOptions as(String alias); FluentSelectColumnOptions cast(String alias); } This can be done with standard Java code but brings some boilerplate code which is cumbersome to maintain. An elegant way to address it is to create a “method dispatcher” that will redirect main methods to the object that supports the main API, and redirect the options ones to the object that supports the options. Creating a Method Dispatcher: Java Proxy Luckily, Java Proxy API helps in being aware of method invocations on an object. As a reminder, a Proxy can be created as such: Proxy.newProxyInstance(classLoader, interfaces, methodHandler) It returns an instance (a "magic" one, thanks to the JVM) that can be typed in one of the interfaces passed as a parameter at any time (the Proxy implements all given interfaces). All methods of all interfaces are intercepted by InvocationHandler.invoke(..) (even equals/hashCode/toString !). So, our goal can be fulfilled if we’re capable of returning a Proxy that implements our interfaces (or the mashup one) and creates an InvocationHandler that propagates calls of the main API to the “main object” and calls the options to the “options object." Since InvocationHandler.invoke(..) gets the invoked Method as an argument, we can easily check if it belongs to one or another of the aforementioned interfaces. This gives the following naïve implementation for our example : Java public static void main(String[] args) { String mySelect = MyFluentQueryAPI.newQuery() .select("a").as("A").cast("char") .add("b").as("B").cast("int") .toString(); System.out.println(mySelect); // will print "[a as A cast char, b as B cast int]", see createFluentSelect() on case "toString" } interface Select { Select add(String s); Select select(String s); } interface ColumnOptions { ColumnOptions as(String s); ColumnOptions cast(String s); } interface FluentSelect extends Select, ColumnOptions { FluentSelect as(String s); FluentSelect cast(String s); FluentSelect add(String s); FluentSelect select(String s); } public static class MyFluentQueryAPI { public static FluentSelect newQuery() { return new MyFluentQueryAPI().createFluentSelect(); } private final SelectSupport selectSupport = new SelectSupport(); public FluentSelect createFluentSelect() { return (FluentSelect) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { FluentSelect.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { switch (method.getName()) { case "as": case "cast": // we look for "as" or "cast" method on ColumnOptions class Method optionMethod = ColumnOptions.class.getMethod(method.getName(), method.getParameterTypes()); // we apply the "as" or "cast" call on element being created optionMethod.invoke(selectSupport.getCurrentElement(), args); break; case "add": case "select": // we look for "add" or "select" method on Select class Method selectMethod = Select.class.getMethod(method.getName(), method.getParameterTypes()); // we apply the "add" or "select" call on the final result (select instance) selectMethod.invoke(selectSupport, args); break; case "toString": return selectSupport.getElements().toString(); } return proxy; } }); } } /** Basic implementation of Select */ static class SelectSupport implements Select { private final List elements = new ArrayList<>(); private SelectedElement currentElement; @Override public Select add(String s) { this.currentElement = new SelectedElement(s); this.elements.add(currentElement); return this; } @Override public Select select(String s) { return add(s); } public SelectedElement getCurrentElement() { return currentElement; } public List getElements() { return elements; } } /** Basic representation of an element of the select clause, implements ColumnOptions */ static class SelectedElement implements ColumnOptions { private String clause; public SelectedElement(String clause) { this.clause = clause; } @Override public ColumnOptions as(String s) { clause += " as " + s; return this; } @Override public ColumnOptions cast(String s) { clause += " cast " + s; return this; } @Override public String toString() { return clause; } } This proof of concept needs to take inheritance into account, as well as argument type compatibility, and even more to make it a robust solution. Stalactite invested that time and created the MethodDispatcher class in the standalone library named Reflection, the final DX for an SQL Query definition is available here, and its usage is here. Stalactite DSL for persistence mapping definition is even more complex; that’s the caveat of all this: creating all the composite interfaces and redirecting correctly all the method calls is a bit complex. That’s why, for the last stage of the rocket, the MethodReferenceDispatcher has been created: it lets one redirect a method reference to some lambda expression to avoid extra code for small interfaces. Its usage can be seen here. Conclusion Implementing a naïve DSL can be straightforward but doesn’t really guide the user-developer. On the other hand, implementing a robust DSL can be cumbersome, Stalactite helped itself by creating an engine for it. While it's not easy to master, it really helps to meet the user-developer experience. Since the engine is the library Reflection, which is out of Stalactite, it can be used in other projects. By Guillaume Mary Digital Garden The topic of note-taking remains relevant today. We know the benefits it provides to the author. We are familiar with various approaches to note-taking and tools that can be used, and we have choices. Imagine you have found your approach, your tool, and your note base is growing and pleasing to the eye. What next? I want to discuss one path of development in this area. This article is dedicated to the concept of a digital garden — the philosophy of publicly maintaining personal notes. My Path For the past 20 years, I have kept notes using methods that lacked systematization, reliability, or usefulness: paper notebooks, text files, Evernote, and other applications whose names have faded from memory. Three years ago, I started using the Zettelkasten style (as I understood and adapted it for myself). I learned about this approach from Rob Muhlestein whom I encountered on Twitch. Experiments led me to my current note-taking method: in the form of Markdown files stored in a Git repository. On my computer, I work with them in VSCode, and on my phone, I use the default "Notes" app. Why not Obsidian? I tried it and decided to stick with VSCode for the following reasons: VSCode is a basic editor that is always open and used for work files. I could not set up Obsidian synchronization via Git, and iCloud synchronization caused app crashes on my phone. I need a quickly accessible app on my phone to jot down fleeting thoughts before, for example, reaching for a roll of toilet paper and experiencing discomfort from waiting. At the same time, I need the note base on my phone much less frequently than the need to urgently write something down. Separating apps for sudden thoughts and the main base has an advantage: it creates a ritual of transferring notes from the phone app to the main base. I review fresh notes, tag them, and add details. This allows me to revisit the recorded thought and increase the chances of not forgetting it. What Is a Digital Garden? The phrase "digital garden" is a metaphor describing an approach to note-taking. It is not just a set of tools like WordPress plugins or Jekyll templates. The idea of a garden is familiar to all of us — it is a place where something grows. Gardens can be very personal and filled with gnome figurines, or they can be sources of food and vitality. And who knows what a sudden visitor to your garden might see? Are you in a lovely pajama with a glass of fresh juice under an apple tree? Or perhaps standing upside down, trying to bring a bit of order and pull out weeds? The digital gardening metaphor emphasizes the slow growth of ideas through writing, rewriting, editing, and revisiting thoughts in a public space. Instead of fixed opinions that never change, this approach allows ideas to develop over time. The goal of digital gardening is to use the collective intelligence of your network to create constructive feedback loops. If done right, you will have an accessible representation of your thoughts that can be "sent out" into the world, and people will be able to respond to it. Even for the most raw ideas, it helps to create a feedback loop to strengthen and fully develop the idea. Core Principles of Gardening Connections over timelines: Gardens are organized around contextual and associative connections; concepts and themes within each note define how they relate to others. The publication date is not the most important aspect of the text. Continuous growth: Gardens never end; they are constantly growing, evolving, and changing, like a real garden. Imperfection: Gardens are inherently imperfect. They do not hide their rough edges and do not claim to be a permanent source of truth. Learning in public: To create constructive feedback loops Personal and experimental: Gardens are inherently heterogeneous. You may plant the same seeds as your neighbor but get a different arrangement of plants. You organize the garden around ideas and means that fit your way of thinking rather than a standard template. Independent ownership: Gardening is about creating your own little corner of the internet that you fully control. Learning in Public This point may raise questions, as it suggests sharing something for free. The approach implies that you publicly document your steps, thoughts, mistakes, and successes in mastering a new topic or skill. This allows you not only to share the result but also to demonstrate the thinking and learning process, which can be useful to others. Besides altruistic motives, personal interest is worth noting. Sometimes I am too lazy to clearly formulate thoughts in notes, which then backfires — I can't understand what I meant. It's amusing how I always rely on my future superpower to decipher my own nonsensical notes — a belief that remains unshakable, though entirely unfounded. But when it comes to others, I don’t allow such naivety. Knowing that my note might not only attract attention but also genuinely help someone motivates me to make an effort and articulate the thought properly. How To Share Today, convenient tools have made creating a fully customizable website much easier. Services like Netlify and Vercel have removed deployment complexities. Static site generators like Jekyll, Gatsby, 11ty, and Next simplify creating complex sites that automatically generate pages and handle load time, image optimization, and SEO. Obsidian offers the ability to publish notes through its subscription platform. Using this service does not feel like "independent ownership." I chose Quartz for myself. It is a free static generator based on Markdown content. Quartz is designed primarily as a tool for publishing digital gardens on the internet. It is simple enough for people without technical experience but powerful enough for customization by experienced developers. My Digital Garden As mentioned, I store my notes in a public Git repository. Most of it is in Russian, with some in English. Changes are automatically published on GitHub Pages and available on my digital garden page. The design, solution scheme, and GitHub Actions scripts are available for review in this note if you want to create something similar. Some use RSS for updates, while I use a Telegram channel for this purpose. It is specifically an update channel, messages are not posted separately. Materials for Further Study The concept has a philosophy and history; I won't retell them but will provide links where you can read more: Maggie Appleton Website GitHub Jacky Zhao GitHub Examples can also be found through a GitHub search if the repository is tagged with the relevant topic. See here for more. Conclusion Establishing a digital garden has been a logical continuation of my journey, starting with the Zettelkasten method. How has it affected me? After the initial effort to set up and deploy the system, I hardly maintain it except for occasional issues. And now I continue to push my notes to Git. The only thing is that I have started to make them more understandable. Thank you for reading the article, and good luck in your quest for organizing thoughts and creating an effective space for ideas! By Anton Belyaev Spring Boot GoT: Game of Trace! When we, developers, find some bugs in our logs, this sometimes is worse than a dragon fight! Let's start with the basics. We have this order of severity of logs, from most detailed to no detail at all: TRACE DEBUG INFO WARN ERROR FATAL OFF The default severity log for your classes is INFO. You don't need to change your configuration file (application.yaml). logging: level: root: INFO Let's create a sample controller to test some of the severity logs: @RestController @RequestMapping("/api") public class LoggingController { private static final Logger logger = LoggerFactory.getLogger(LoggingController.class); @GetMapping("/test") public String getTest() { testLogs(); return "Ok"; } public void testLogs() { System.out.println(" ==== LOGS ==== "); logger.error("This is an ERROR level log message!"); logger.warn("This is a WARN level log message!"); logger.info("This is an INFO level log message!"); logger.debug("This is a DEBUG level log message!"); logger.trace("This is a TRACE level log message!"); } } We can test it with HTTPie or any other REST client: Shell $ http GET :8080/api/test HTTP/1.1 200 Ok Checking in Spring Boot logs, we will see something like this: PowerShell ==== LOGS ==== 2024-09-08T20:50:15.872-03:00 ERROR 77555 --- [nio-8080-exec-5] LoggingController : This is an ERROR level log message! 2024-09-08T20:50:15.872-03:00 WARN 77555 --- [nio-8080-exec-5] LoggingController : This is a WARN level log message! 2024-09-08T20:50:15.872-03:00 INFO 77555 --- [nio-8080-exec-5] LoggingController : This is an INFO level log message! If we need to change it to DEBUG all my com.boaglio classes, we need to add this info to the application.yaml file and restart the application: logging: level: com.boaglio: DEBUG Now repeating the test, we will see a new debug line: PowerShell ==== LOGS ==== 2024-09-08T20:56:35.082-03:00 ERROR 81780 --- [nio-8080-exec-1] LoggingController : This is an ERROR level log message! 2024-09-08T20:56:35.082-03:00 WARN 81780 --- [nio-8080-exec-1] LoggingController : This is a WARN level log message! 2024-09-08T20:56:35.083-03:00 INFO 81780 --- [nio-8080-exec-1] LoggingController : This is an INFO level log message! 2024-09-08T20:56:35.083-03:00 DEBUG 81780 --- [nio-8080-exec-1] LoggingController : This is a DEBUG level log message! This is good, but sometimes we are running in production and we need to change from INFO to TRACE, just for quick research. This is possible with the LoggingSystem class. Let's add to our controller a POST API to change all logs to TRACE: @Autowired private LoggingSystem loggingSystem; @PostMapping("/trace") public void setLogLevelTrace() { loggingSystem.setLogLevel("com.boaglio",LogLevel.TRACE); logger.info("TRACE active"); testLogs(); } We are using the LoggingSystem.setLogLevel method, changing all logs from the package com.boaglio to TRACE. Let's try to call out POST API to enable TRACE: Shell $ http POST :8080/api/trace HTTP/1.1 200 Now we can check that the trace was finally enabled: PowerShell 2024-09-08T21:04:03.791-03:00 INFO 82087 --- [nio-8080-exec-3] LoggingController : TRACE active ==== LOGS ==== 2024-09-08T21:04:03.791-03:00 ERROR 82087 --- [nio-8080-exec-3] LoggingController : This is an ERROR level log message! 2024-09-08T21:04:03.791-03:00 WARN 82087 --- [nio-8080-exec-3] LoggingController : This is a WARN level log message! 2024-09-08T21:04:03.791-03:00 INFO 82087 --- [nio-8080-exec-3] LoggingController : This is an INFO level log message! 2024-09-08T21:04:03.791-03:00 DEBUG 82087 --- [nio-8080-exec-3] LoggingController : This is a DEBUG level log message! 2024-09-08T21:04:03.791-03:00 TRACE 82087 --- [nio-8080-exec-3] LoggingController : This is a TRACE level log message! And a bonus tip here, to enable DEBUG or TRACE just for the Spring Boot framework (which is great sometimes to understand what is going on under the hood), we can simply add this to our application.yaml: Shell debug:true or trace: true Let the game of trace begin! By Fernando Boaglio Explainable AI (XAI): How Developers Build Trust and Transparency in AI Systems Developers working on Explainable AI (XAI) must address several key aspects, such as the problem, boundary scope, and potential solutions of XAI, as well as some specific use cases and benefits that can enhance an organization's credibility when implementing or leveraging this technology. The more AI is incorporated into different sectors, developers play a critical role in making those systems interpretable and transparent. XAI is crucial in making AI models highly interpretable and debuggable; it also guarantees responsible use of highly complex AI technologies, which should be fair, transparent, and accountable to society's users and stakeholders. Importance of Explainability in AI The first issue with the development of AI is to make this technology transparent and explainable. According to a McKinsey Global Institute report, AI could add $2.6 trillion-$4.4 trillion annually in global corporate profits, and the World Economic Forum estimates an economic contribution for the same amounting to up to $15.7 trillion by 2030. This is a good reminder of AI's ever-growing impact on our society and why it's absolutely mandatory to build systems that are powerful but also explainable and trustworthy. Developer's View on Explainable AI Complexity vs. Interpretability The biggest challenge developers need help with regarding XAI is the tug-and-pull relationship between complexity (accurate models) and interpretability goals. Deep learning, ensemble methods, and Support Vector Machines (SVMs) are a few of the most accurate AI/ML models. On the downside, these models are often considered "black boxes," and decisions emanating from them become difficult to understand. This makes it all the more challenging for developers to accommodate this complexity and provide meaningful explanations about their functioning without hampering the performance of a model. Nascent Techniques XAI tools are immature, as the practice of explainability is new. These need to achieve more transparency to instill trust mechanisms in AI systems. However, some post-hoc explainability methods like SHAP and LIME offer insight into decision-making processes by a model. Tailoring Explanations to Context Another challenge for developers is putting the explanation in context. Machine learning models are typically deployed in various environments aimed at different user groups, with levels from the most erudite technical ones to users who require the utmost simplicity. The XAI system will vary based on the type of user requesting an explanation. Scope Interpretable Models Developers use some inherently interpretable models such as decision trees, linear models, or rule-based systems. Even if these models are less complex and feature-reduced, they provide explicit decision pathways. Post-Hoc Explainability It keeps the structure of black-box models, but developers can explain predictions using techniques such as SHAP, LIME, or feature importance visualizations. For example, when building an autonomous vehicle, the decisions made by the model installed in each car must be sensible (because it has to do with safety!). Deep learning models can be used on perception tasks but with post-hoc explanations. Algorithmic Transparency This is especially important in XAI, where the sector will fall under huge legal or ethical liabilities due to a decision made by an opaque AI. Wherever decisions are accountable, the algorithm also has to be! AI governance requires developers to ensure their AI models meet regulatory and ethical standards by providing clear, understandable explanations for how decisions are rendered. Benefits At this core, XAI builds trust with users and stakeholders in development efforts. Also, concerning high-stakes decisions, XAI independently facilitates trust-building between AI systems. The job of XAI in this age is to inform its users how their AI has managed contrast predictions. This is even more pronounced in a field like finance, where necessity could tie your model's output to investment health and allow you to make better decisions or risk forecasts so that you do not lose. Ultimately, XAI builds public trust by demonstrating that organizations have very tight and explainable AI systems. For instance, in the industries where AI can decide on finance, healthcare, or legal services, to name just a few — this fact drives other conceptual moments within XAI. However, at least those have explainable and localized results. XAI is for building consumer confidence around AI, which, in turn, needs to be overcome before it can expect any of the population to go out and start using technology with AI in general. Ethics and responsibilities are the main subjects of any state-of-the-art AI deployment that requires. Explainable AI is one way to ensure an ethical and responsible deployment of the AV model, ensuring that our algorithm does not behave like a black box where biases are stuck. Conclusion Thus, developers are key to furthering XAI by tackling the problem of designing AI systems with power and interpretability. This improves the usability and adoption of AI technologies and helps organizations generate trust in the marketplace. XAI is a technical necessity and a notable advantage that will enable deploying more AI systems in trust, compliance with regulations, and ethics, leaving room for further growth and broader influence across different industries. By Suri Nuthalapati CORE Exploring Real-Time Data Ingestion Into Snowflake Using CockroachDB, Redpanda, and Kafka Connect Previous Articles on Snowflake Tour of Snowflake ingestion using CockroachDB and Redpanda Connect Integrating Snowflake with Trino Previous Articles on CockroachDB CDC Emitting Protocol Buffers with CockroachDB CDC Queries Using CockroachDB CDC with Apache Pulsar Using CockroachDB CDC with Azure Event Hubs SaaS Galore: Integrating CockroachDB with Confluent Kafka, FiveTran, and Snowflake Using CockroachDB CDC with Confluent Cloud Kafka and Schema Registry CockroachDB CDC using Minio as cloud storage sink CockroachDB CDC using Hadoop Ozone S3 Gateway as cloud storage sink Motivation This article builds upon the previous discussion in "Tour of Snowflake ingestion using CockroachDB and Redpanda Connect," where we investigated the process of streaming changefeeds from CockroachDB to Snowflake using Redpanda Connect and Snowpipe in batch mode. Here, we will shift our focus to Kafka Connect and demonstrate how both batch and streaming modes can be utilized for data ingestion into Snowflake. Overview Deploy a CockroachDB cluster with enterprise changefeeds Deploy Snowflake Deploy Kafka Connect Verify Conclusion Detailed Instructions Deploy a CockroachDB Cluster With Enterprise Changefeeds Start by either launching a CockroachDB instance or utilizing a managed service. To enable CDC, execute the following commands: SET CLUSTER SETTING cluster.organization = ''; SET CLUSTER SETTING enterprise.license = ''; SET CLUSTER SETTING kv.rangefeed.enabled = true; Verify that changefeeds are enabled: SHOW CLUSTER SETTING kv.rangefeed.enabled; If the value is false, update it to true. Create a source table: CREATE TABLE cockroachdb ( id INT PRIMARY KEY, value STRING DEFAULT md5(random()::text), created_at TIMESTAMPTZ DEFAULT now(), updated_at TIMESTAMPTZ DEFAULT NULL); Insert random data: INSERT INTO cockroachdb SELECT (generate_series(1, 10000)); Update a row: UPDATE cockroachdb SET value = 'UPDATED', updated_at = now() WHERE id = 1; Create a changefeed job pointing to a local instance of Redpanda: CREATE CHANGEFEED FOR TABLE cockroachdb INTO 'kafka://redpanda:29092'; Inspect the data: SELECT * FROM cockroachdb LIMIT 5; id | value | created_at | updated_at -----+----------------------------------+-------------------------------+-------------------------------- 1 | UPDATED | 2024-09-09 13:17:57.837984+00 | 2024-09-09 13:17:57.917108+00 2 | 27a41183599c44251506e2971ba78426 | 2024-09-09 13:17:57.837984+00 | NULL 3 | 3bf8bc26a750a15691ec4d7ddbb7f5e5 | 2024-09-09 13:17:57.837984+00 | NULL 4 | b8c5786e8651ddfb3a68eabeadb52f2e | 2024-09-09 13:17:57.837984+00 | NULL 5 | 3a24df165773639ce89d0d877e7103b7 | 2024-09-09 13:17:57.837984+00 | NULL (5 rows) The next step is to set up the Snowflake Kafka connector. Deploy Snowflake Create a database and schema for outputting changefeed data: USE ROLE SYSADMIN; CREATE OR REPLACE DATABASE KAFKADB; CREATE OR REPLACE SCHEMA kafka_schema; Follow the Snowflake documentation to configure the Kafka connector. Create the necessary tables: create or replace table kafkatb_batch( RECORD_METADATA VARIANT, RECORD_CONTENT VARIANT ); create or replace table kafkatb_streaming( RECORD_METADATA VARIANT, RECORD_CONTENT VARIANT ); Set up roles and permissions: -- Use a role that can create and manage roles and privileges. USE ROLE securityadmin; -- Create a Snowflake role with the privileges to work with the connector. CREATE OR REPLACE ROLE kafka_connector_role_1; -- Grant privileges on the database. GRANT USAGE ON DATABASE kafkadb TO ROLE kafka_connector_role_1; -- Grant privileges on the schema. GRANT USAGE ON SCHEMA KAFKADB.kafka_schema TO ROLE kafka_connector_role_1; GRANT CREATE TABLE ON SCHEMA KAFKADB.kafka_schema TO ROLE kafka_connector_role_1; GRANT CREATE STAGE ON SCHEMA KAFKADB.kafka_schema TO ROLE kafka_connector_role_1; GRANT CREATE PIPE ON SCHEMA KAFKADB.kafka_schema TO ROLE kafka_connector_role_1; -- Only required if the Kafka connector will load data into an existing table. GRANT OWNERSHIP ON TABLE KAFKADB.KAFKA_SCHEMA.kafkatb_batch TO ROLE kafka_connector_role_1; GRANT OWNERSHIP ON TABLE KAFKADB.KAFKA_SCHEMA.kafkatb_streaming TO ROLE kafka_connector_role_1; -- Grant the custom role to an existing user. GRANT ROLE kafka_connector_role_1 TO USER username; -- Set the custom role as the default role for the user. -- If you encounter an 'Insufficient privileges' error, verify the role that has the OWNERSHIP privilege on the user. ALTER USER username SET DEFAULT_ROLE = kafka_connector_role_1; Ensure you follow the documentation for setting up key pair authentication for the Snowflake Kafka connector. Deploy Kafka Connect Run Redpanda using Docker Compose. docker compose -f compose-redpandadata.yaml up -d Once up, navigate to the Redpanda Console. Click into the cockroachdb topic: Install the Snowflake Kafka connector: confluent-hub install --no-prompt snowflakeinc/snowflake-kafka-connector:latest Use the following configuration for Kafka Connect in distributed mode, saved as connect-distributed.properties: bootstrap.servers=172.18.0.3:29092 group.id=connect-cluster key.converter=org.apache.kafka.connect.json.JsonConverter value.converter=org.apache.kafka.connect.json.JsonConverter key.converter.schemas.enable=true value.converter.schemas.enable=true offset.storage.topic=connect-offsets offset.storage.replication.factor=1 config.storage.topic=connect-configs config.storage.replication.factor=1 status.storage.topic=connect-status status.storage.replication.factor=1 offset.flush.interval.ms=10000 plugin.path=/usr/share/confluent-hub-components,plugin.path=/usr/local/share/kafka/plugins,/usr/share/filestream-connectors Deploy Kafka Connect in distributed mode: ./kafka-connect/bin/connect-distributed.sh connect-distributed.properties Register the Snowflake connector with the following configuration, saved as snowflake-sink-batch.json: { "name":"snowflake-sink-batch", "config":{ "connector.class":"com.snowflake.kafka.connector.SnowflakeSinkConnector", "tasks.max":"8", "topics":"cockroachdb", "snowflake.topic2table.map": "cockroachdb:kafkatb_batch", "buffer.count.records":"10000", "buffer.flush.time":"60", "buffer.size.bytes":"5000000", "snowflake.url.name":"account-name:443", "snowflake.user.name":"username", "snowflake.private.key":"private-key", "snowflake.private.key.passphrase":"", "snowflake.database.name":"kafkadb", "snowflake.schema.name":"kafka_schema", "snowflake.role.name":"kafka_connector_role_1", "key.converter":"org.apache.kafka.connect.storage.StringConverter", "value.converter":"com.snowflake.kafka.connector.records.SnowflakeJsonConverter" } } Publish the connector configuration: curl -d @"snowflake-sink-batch.json" -H "Content-Type: application/json" -X POST http://kafka-connect:8083/connectors Verify the connector in the Kafka Connect UI and in the Kafka Connect section of the Redpanda Console. If you click on the snowflake-sink-batch sink, you can see additional information. The comprehensive steps needed to set this up are thoroughly outlined in the tutorial. Data will now flow into Snowflake in batch mode, with updates occurring every 60 seconds as determined by the buffer.flush.time parameter. You can now query the data in Snowflake: select * from kafkatb_batch limit 5; If everything is configured correctly, the data from CockroachDB should be available in Snowflake in real-time or in batches, depending on your configuration. record_metadata: { "CreateTime": 1725887877966, "key": "[3]", "offset": 30007, "partition": 0, "topic": "cockroachdb" } record_content: { "after": { "created_at": "2024-09-09T13:17:57.837984Z", "id": 1, "updated_at": "2024-09-09T13:17:57.917108Z", "value": "UPDATED" } } The next step is to configure the connector in streaming mode. First, stop the current connector with the following command: curl -X DELETE http://localhost:8083/connectors/snowflake-sink-batch The updated connector configuration will appear as follows: { "name":"snowflake-sink-streaming", "config":{ "connector.class":"com.snowflake.kafka.connector.SnowflakeSinkConnector", "tasks.max":"8", "topics":"cockroachdb", "snowflake.topic2table.map": "cockroachdb:kafkatb_streaming", "buffer.count.records":"10000", "buffer.flush.time":"10", "buffer.size.bytes":"5000000", "snowflake.url.name":":443", "snowflake.user.name":"username", "snowflake.private.key":"private-key", "snowflake.private.key.passphrase":"", "snowflake.database.name":"kafkadb", "snowflake.schema.name":"kafka_schema", "snowflake.role.name":"kafka_connector_role_1", "key.converter":"org.apache.kafka.connect.storage.StringConverter", "value.converter":"org.apache.kafka.connect.json.JsonConverter", "value.converter.schemas.enable":"false", "snowflake.ingestion.method": "SNOWPIPE_STREAMING", "errors.log.enable":"true", "schemas.enable":"false" } } Take note of the snowflake.ingestion.method parameter. This feature removes the need to wait 60 seconds to push data to Snowflake, allowing us to reduce the buffer.flush.time to 10 seconds. To deploy the connector, use the following command: curl -d @"snowflake-sink-streaming.json" -H "Content-Type: application/json" -X POST http://kafka-connect:8083/connectors Shortly after deployment, the data will be available in the Snowflake table. The previous examples demonstrated how data was ingested into predefined Snowflake tables. The following method will automatically infer the schema from the Kafka messages: { "name":"snowflake-sink-streaming-schematized", "config":{ "connector.class":"com.snowflake.kafka.connector.SnowflakeSinkConnector", "tasks.max":"8", "topics":"cockroachdb", "snowflake.topic2table.map": "cockroachdb:kafkatb_streaming_schematized", "buffer.count.records":"10000", "buffer.flush.time":"10", "buffer.size.bytes":"5000000", "snowflake.url.name":":443", "snowflake.user.name":"username", "snowflake.private.key":"private-key", "snowflake.private.key.passphrase":"", "snowflake.database.name":"kafkadb", "snowflake.schema.name":"kafka_schema", "snowflake.role.name":"kafka_connector_role_1", "key.converter":"org.apache.kafka.connect.storage.StringConverter", "value.converter":"org.apache.kafka.connect.json.JsonConverter", "value.converter.schemas.enable":"false", "snowflake.ingestion.method": "SNOWPIPE_STREAMING", "errors.log.enable":"true", "schemas.enable":"false", "snowflake.enable.schematization": "TRUE" } } Save this as snowflake-sink-streaming-schematized.json and deploy it using: curl -d @"snowflake-sink-streaming-schematized.json" -H "Content-Type: application/json" -X POST http://kafka-connect:8083/connectors Upon deployment, a new table will be created in Snowflake with the following schema: create or replace TABLE KAFKADB.KAFKA_SCHEMA.KAFKATB_STREAMING_SCHEMATIZED ( RECORD_METADATA VARIANT COMMENT 'created by automatic table creation from Snowflake Kafka Connector', AFTER VARIANT COMMENT 'column created by schema evolution from Snowflake Kafka Connector' ); To inspect the table, use the following query: SELECT after AS record FROM kafkatb_streaming_schematized LIMIT 5; Sample result: { "created_at": "2024-09-09T16:39:34.993226Z", "id": 18712, "updated_at": null, "value": "0d6bd8a4a790aab95c97a084d17bd820" } Verify We can flatten the data for easier manipulation using the following query: USE ROLE securityadmin; GRANT CREATE VIEW ON SCHEMA KAFKADB.kafka_schema TO ROLE kafka_connector_role_1; USE ROLE kafka_connector_role_1; USE DATABASE KAFKADB; USE SCHEMA KAFKA_SCHEMA; CREATE VIEW v_kafkatb_batch_flattened AS SELECT PARSE_JSON(record_content:after):id AS ID, PARSE_JSON(record_content:after):value AS VALUE, PARSE_JSON(record_content:after):created_at AS CREATED_AT, PARSE_JSON(record_content:after):updated_at AS UPDATED_AT FROM kafkatb_batch; SELECT * FROM v_kafkatb_batch_flattened limit 1; ID VALUE CREATED_AT UPDATED_AT 1 "UPDATED" "2024-09-09T13:17:57.837984Z" "2024-09-09T13:17:57.917108Z" Alternatively, for the schematized table, the view creation statement would be: CREATE VIEW v_kafkatb_streaming_schematized_flattened AS SELECT PARSE_JSON(after):id AS ID, PARSE_JSON(after):value AS VALUE, PARSE_JSON(after):created_at AS CREATED_AT, PARSE_JSON(after):updated_at AS UPDATED_AT FROM kafkatb_streaming_schematized; To verify the data flow, make an update in CockroachDB and check for the changes in Snowflake: UPDATE cockroachdb SET value = 'UPDATED', updated_at = now() WHERE id = 20000; In Snowflake, execute the following query to confirm the update: SELECT * FROM v_kafkatb_streaming_schematized_flattened where VALUE = 'UPDATED'; Sample result: ID VALUE CREATED_AT UPDATED_AT 20000 "UPDATED" "2024-09-09T18:15:13.460078Z" "2024-09-09T18:16:56.550778Z" 19999 "UPDATED" "2024-09-09T18:15:13.460078Z" "2024-09-09T18:15:27.365272Z" The architectural diagram is below: Conclusion In this process, we explored Kafka Connect as a solution to stream changefeeds into Snowflake. This approach provides greater control over how messages are delivered to Snowflake, leveraging the Snowflake Kafka Connector with Snowpipe Streaming for real-time, reliable data ingestion. By Artem Ervits CORE REST and HTTP Semantics Roy Fielding created REST as his doctorate dissertation. After reading it, I would boil it down to three basic elements: A document that describes object state A transport mechanism to transmit the object state back and forth between systems A set of operations to perform on the state While Roy was focused solely on HTTP, I don't see why another transport could not be used. Here are some examples: Mount a WebDAV share (WebDAV is an HTTP extension, so is still using HTTP). Copy a spreadsheet (.xls, .xlsx, .csv, .ods) into the mounted folder, where each row is the new/updated state. The act of copying into the share indicates the operation of upserting, the name of the file indicates the type of data, and the columns are the fields. The server responds with (document name)-status.(document suffix), which provides a key for each row, a status, and possibly an error message. In this case, it does not really make sense to request data. Use gRPC. The object transmitted is the document, HTTP is the transport, and the name of the remote method is the operation. Data can be both provided and requested. Use FTP. Similar to WebDAV, it is file-based. The PUT command is upserting, and the GET command is requesting. GET only provides a filename, so it generally provides all data of the specified type. It is possible to allow for special filenames that indicate a hard-coded filter to GET a subset of data. Whenever I see REST implementations in the wild, they often do not follow basic HTTP semantics, and I have never seen any explanation given for this, just a bunch of varying opinions. None of those I found referenced the RFC. Most seem to figure that: POST = Create PUT = Update the whole document PATCH = Update a portion of a document GET = Retrieve the whole document This is counter to what HTTP states regarding POST and PUT: PUT is "create" or "update". GET generally returns whatever was last PUT. If PUT creates, it MUST return 201 Created. If PUT updates, it MUST return 200 OK or 204 No Content. The RFC suggests the content for 200 OK of a PUT should be the status of the action. I think it would ok in the case of SQL to return the new row from a select statement. This has the advantage that any generated columns are returned to the caller without having to perform a separate GET. POST processes a resource according to its own semantics. Older RFCs said POST is for subordinates of a resource. All versions give the example of posting an article to a mailing list; all versions say if a resource is created that 201 Created SHOULD be returned. I would argue that effectively what POST really means is: Any data manipulation except create, full/partial update, or delete Any operation that is not data manipulation, such as: Perform a full-text search for rows that match a phrase. Generate a GIS object to display on a map. The word MUST means your implementation is only HTTP compliant if you do what is stated. Using PUT only for updates obviously won't break anything, just because it isn't RFC compliant. If you provide clients that handle all the details of sending/receiving data, then what verbs get used won't matter much to the user of the client. I'm the kind of guy who wants a reason for not following the RFC. I have never understood the importance of separating create from update in REST APIs, any more than in web apps. Think about cell phone apps like calendar appointments, notes, contacts, etc: "Create" is hitting the plus icon, which displays a new form with empty or default values. "Update" is selecting an object and hitting the pencil icon, which displays an entry form with current values. Once the entry form appears, it works exactly the same in terms of field validations. So why should REST APIs and web front ends be any different than cell phone apps? If it is helpful for phone users to get the same data entry form for "create" and "update," wouldn't it be just as helpful to API and web users? If you decide to use PUT as "create" or "update", and you're using SQL as a store, most vendors have an upsert query of some sort. Unfortunately, that does not help to decide when to return 200 OK or 201 Created. You'd have to look at the information your driver provides when a DML query executes to find a way to distinguish insert from update for an upsert or use another query strategy. A simple example would be to perform an update set ... where pk column = pk value. If one row was affected, then the row exists and was updated; otherwise, the row does not exist and an insert is needed. On Postgres, you can take advantage of the RETURNING clause, which can actually return anything, not just row data, as follows: SQL INSERT INTO