Krones provides breweries, beverage bottlers, and food producers all over the world with individual machines and complete production lines. Every day, millions of glass bottles, cans, and PET containers run through a Krones line. Production lines are complex systems with lots of possible errors that could stall the line and decrease the production yield. Krones wants to detect the failure as early as possible (sometimes even before it happens) and notify production line operators to increase reliability and output. So how to detect a failure? Krones equips their lines with sensors for data collection, which can then be evaluated against rules. Krones, as the line manufacturer, as well as the line operator have the possibility to create monitoring rules for machines. Therefore, beverage bottlers and other operators can define their own margin of error for the line. In the past, Krones used a system based on a time series database. The main challenges were that this system was hard to debug and also queries represented the current state of machines but not the state transitions.
This post shows how Krones built a streaming solution to monitor their lines, based on Amazon Kinesis and Amazon Managed Service for Apache Flink. These fully managed services reduce the complexity of building streaming applications with Apache Flink. Managed Service for Apache Flink manages the underlying Apache Flink components that provide durable application state, metrics, logs, and more, and Kinesis enables you to cost-effectively process streaming data at any scale. If you want to get started with your own Apache Flink application, check out the GitHub repository for samples using the Java, Python, or SQL APIs of Flink.
Overview of solution
Krones’s line monitoring is part of the Krones Shopfloor Guidance system. It provides support in the organization, prioritization, management, and documentation of all activities in the company. It allows them to notify an operator if the machine is stopped or materials are required, regardless where the operator is in the line. Proven condition monitoring rules are already built-in but can also be user defined via the user interface. For example, if a certain data point that is monitored violates a threshold, there can be a text message or trigger for a maintenance order on the line.
The condition monitoring and rule evaluation system is built on AWS, using AWS analytics services. The following diagram illustrates the architecture.
Almost every data streaming application consists of five layers: data source, stream ingestion, stream storage, stream processing, and one or more destinations. In the following sections, we dive deeper into each layer and how the line monitoring solution, built by Krones, works in detail.
Data source
The data is gathered by a service running on an edge device reading several protocols like Siemens S7 or OPC/UA. Raw data is preprocessed to create a unified JSON structure, which makes it easier to process later on in the rule engine. A sample payload converted to JSON might look like the following:
AWS IoT Greengrass is an open source Internet of Things (IoT) edge runtime and cloud service. This allows you to act on data locally and aggregate and filter device data. AWS IoT Greengrass provides prebuilt components that can be deployed to the edge. The production line solution uses the stream manager component, which can process data and transfer it to AWS destinations such as AWS IoT Analytics, Amazon Simple Storage Service (Amazon S3), and Kinesis. The stream manager buffers and aggregates records, then sends it to a Kinesis data stream.
Stream storage
The job of the stream storage is to buffer messages in a fault tolerant way and make it available for consumption to one or more consumer applications. To achieve this on AWS, the most common technologies are Kinesis and Amazon Managed Streaming for Apache Kafka (Amazon MSK). For storing our sensor data from production lines, Krones choose Kinesis. Kinesis is a serverless streaming data service that works at any scale with low latency. Shards within a Kinesis data stream are a uniquely identified sequence of data records, where a stream is composed of one or more shards. Each shard has 2 MB/s of read capacity and 1 MB/s write capacity (with max 1,000 records/s). To avoid hitting those limits, data should be distributed among shards as evenly as possible. Every record that is sent to Kinesis has a partition key, which is used to group data into a shard. Therefore, you want to have a large number of partition keys to distribute the load evenly. The stream manager running on AWS IoT Greengrass supports random partition key assignments, which means that all records end up in a random shard and the load is distributed evenly. A disadvantage of random partition key assignments is that records aren’t stored in order in Kinesis. We explain how to solve this in the next section, where we talk about watermarks.
Watermarks
A watermark is a mechanism used to track and measure the progress of event time in a data stream. The event time is the timestamp from when the event was created at the source. The watermark indicates the timely progress of the stream processing application, so all events with an earlier or equal timestamp are considered as processed. This information is essential for Flink to advance event time and trigger relevant computations, such as window evaluations. The allowed lag between event time and watermark can be configured to determine how long to wait for late data before considering a window complete and advancing the watermark.
Krones has systems all around the globe, and needed to handle late arrivals due to connection losses or other network constraints. They started out by monitoring late arrivals and setting the default Flink late handling to the maximum value they saw in this metric. They experienced issues with time synchronization from the edge devices, which lead them to a more sophisticated way of watermarking. They built a global watermark for all the senders and used the lowest value as the watermark. The timestamps are stored in a HashMap for all incoming events. When the watermarks are emitted periodically, the smallest value of this HashMap is used. To avoid stalling of watermarks by missing data, they configured an idleTimeOut parameter, which ignores timestamps that are older than a certain threshold. This increases latency but gives strong data consistency.
public class BucketWatermarkGenerator implements WatermarkGenerator<DataPointEvent> {
private HashMap <String, WatermarkAndTimestamp> lastTimestamps;
private Long idleTimeOut;
private long maxOutOfOrderness;
}
Stream processing
After the data is collected from sensors and ingested into Kinesis, it needs to be evaluated by a rule engine. A rule in this system represents the state of a single metric (such as temperature) or a collection of metrics. To interpret a metric, more than one data point is used, which is a stateful calculation. In this section, we dive deeper into the keyed state and broadcast state in Apache Flink and how they’re used to build the Krones rule engine.
Control stream and broadcast state pattern
In Apache Flink, state refers to the ability of the system to store and manage information persistently across time and operations, enabling the processing of streaming data with support for stateful computations.
The broadcast state pattern allows the distribution of a state to all parallel instances of an operator. Therefore, all operators have the same state and data can be processed using this same state. This read-only data can be ingested by using a control stream. A control stream is a regular data stream, but usually with a much lower data rate. This pattern allows you to dynamically update the state on all operators, enabling the user to change the state and behavior of the application without the need for a redeploy. More precisely, the distribution of the state is done by the use of a control stream. By adding a new record into the control stream, all operators receive this update and are using the new state for the processing of new messages.
This allows users of Krones application to ingest new rules into the Flink application without restarting it. This avoids downtime and gives a great user experience as changes happen in real time. A rule covers a scenario in order to detect a process deviation. Sometimes, the machine data is not as easy to interpret as it might look at first glance. If a temperature sensor is sending high values, this might indicate an error, but also be the effect of an ongoing maintenance procedure. It’s important to put metrics in context and filter some values. This is achieved by a concept called grouping.
Grouping of metrics
The grouping of data and metrics allows you to define the relevance of incoming data and produce accurate results. Let’s walk through the example in the following figure.
In Step 1, we define two condition groups. Group 1 collects the machine state and which product is going through the line. Group 2 uses the value of the temperature and pressure sensors. A condition group can have different states depending on the values it receives. In this example, group 1 receives data that the machine is running, and the one-liter bottle is selected as the product; this gives this group the state ACTIVE. Group 2 has metrics for temperature and pressure; both metrics are above their thresholds for more than 5 minutes. This results in group 2 being in a WARNING state. This means group 1 reports that everything is fine and group 2 does not. In Step 2, weights are added to the groups. This is needed in some situations, because groups might report conflicting information. In this scenario, group 1 reports ACTIVE and group 2 reports WARNING, so it’s not clear to the system what the state of the line is. After adding the weights, the states can be ranked, as shown in step 3. Lastly, the highest ranked state is chosen as the winning one, as shown in Step 4.
After the rules are evaluated and the final machine state is defined, the results will be further processed. The action taken depends on the rule configuration; this can be a notification to the line operator to restock materials, do some maintenance, or just a visual update on the dashboard. This part of the system, which evaluates metrics and rules and takes actions based on the results, is referred to as a rule engine.
Scaling the rule engine
By letting users build their own rules, the rule engine can have a high number of rules that it needs to evaluate, and some rules might use the same sensor data as other rules. Flink is a distributed system that scales very well horizontally. To distribute a data stream to several tasks, you can use the keyBy() method. This allows you to partition a data stream in a logical way and send parts of the data to different task managers. This is often done by choosing an arbitrary key so you get an evenly distributed load. In this case, Krones added a ruleId to the data point and used it as a key. Otherwise, data points that are needed are processed by another task. The keyed data stream can be used across all rules just like a regular variable.
Destinations
When a rule changes its state, the information is sent to a Kinesis stream and then via Amazon EventBridge to consumers. One of the consumers creates a notification from the event that is transmitted to the production line and alerts the personnel to act. To be able to analyze the rule state changes, another service writes the data to an Amazon DynamoDB table for fast access and a TTL is in place to offload long-term history to Amazon S3 for further reporting.
Conclusion
In this post, we showed you how Krones built a real-time production line monitoring system on AWS. Managed Service for Apache Flink allowed the Krones team to get started quickly by focusing on application development rather than infrastructure. The real-time capabilities of Flink enabled Krones to reduce machine downtime by 10% and increase efficiency up to 5%.
Florian Mair is a Senior Solutions Architect and data streaming expert at AWS. He is a technologist that helps customers in Europe succeed and innovate by solving business challenges using AWS Cloud services. Besides working as a Solutions Architect, Florian is a passionate mountaineer, and has climbed some of the highest mountains across Europe.
Emil Dietl is a Senior Tech Lead at Krones specializing in data engineering, with a key field in Apache Flink and microservices. His work often involves the development and maintenance of mission-critical software. Outside of his professional life, he deeply values spending quality time with his family.
Simon Peyer is a Solutions Architect at AWS based in Switzerland. He is a practical doer and is passionate about connecting technology and people using AWS Cloud services. A special focus for him is data streaming and automations. Besides work, Simon enjoys his family, the outdoors, and hiking in the mountains.
Everyone knows we’re living through an exceptional time when it comes to media production: Every day we experience a tidal wave of content—social video, virtual reality (VR) and augmented reality (AR) gaming, 10K sports footage, every streaming option imaginable—crashing down on us.
Two eye popping stats underscore that this perception is real: In December, Netflix shared that its users streamed close to 100 billion hours of content on its platform during the first half of 2023. At the beginning of 2024, YouTube revealed that its users watch one billion hours of video daily.
It’s hard to make sense of that volume of content, it’s even harder to understand how it’s produced. Imagine the armies of people and types of programs required to capture, ingest, transcode, store, tag, edit, distribute, and archive all of it. Managing that content means touching every stage, start to finish, of the production process through the data lifecycle.
To further complicate things, the modern production person’s workflow is nothing close to linear. They have to deal with:
A diversity of inputs: Content is pouring in from various sources. Keeping track of all this content, ensuring its quality, and organizing it effectively can feel like trying to catch a waterfall in a teacup.
A variety of formats and file types: Each platform or device may require a different format or resolution, making it difficult to maintain consistency across the board and adding another layer of complexity.
Managing metadata, or indexing and tagging: With so much content flying around, ensuring that each file is properly tagged with relevant information is crucial for easy retrieval and management. However, manually inputting metadata for every piece of media can be time-consuming and prone to errors.
Remote and in-person collaboration: With team members spread across different locations, coordinating efforts and maintaining version control can be a headache.
Storage and scalability: As the volume of media grows, so does the need for storage space. Finding a solution that can accommodate this growth without breaking the bank can be tough.
While many companies are jumping in to provide tools to manage this tidal wave of content, one company, Backlight iconik, differentiates itself by providing industry-leading tools and offering public media reports on the state of media data today.
Backlight iconik’s 2024 Media Stats Report
Since 2018, iconik has provided a cloud-based media asset management (MAM) tool to help production professionals tame the insanity of modern content development. For the past four years, they’ve also provided an annual Media Stats report to help the industry understand the type of media being developed and distributed, as well as where and how it’s stored. (In 2022, Backlight, a global media technology, acquired iconik, hence the name change.) If you want the full story, please check out Backlight iconik’s 2024 Media Stats Report,
As cloud storage specialists here at Backblaze (and, lovers of stats ourselves), we would like to dig into their stats on storage and offer our own take here for you today.
2024 Media Storage Trend: The Content Tidal Wave Is Not a Mirage
According to Backlight iconik’s Media Stats Report, iconik’s data exploded to 152PB, shooting up by a whopping 57%—that’s 53PB more than in 2023. To put it in perspective, that’s roughly 6TB of fresh data pouring in every hour. This surge in data can be attributed to both new customers integrating their archives with iconik and existing customers ramping up their usage.
2024 Media Storage Trend: Audio on the Rise
An interesting find in their study was the difference between audio and video asset growth. Iconik is now managing 328 years of video (up 41% YoY) and 208 years of audio (up 50% YoY).
Note that “duration” in this context is measuring the total hours of runtime for each file. Source.
Over the last year, the growth of audio assets managed by Backlight iconik has surged, surpassing that of video, with a staggering 1,700 hours being added daily. They believe this surge is closely tied to the remarkable expansion of both the podcasting and audiobook markets in recent years. The global podcast market ballooned to $17.9 billion in 2023 and is forecasted to soar to $144 billion by 2032. Similarly, the audiobook market is projected to hit $35 billion by 2030, with expected revenue of $35.05 billion in the same year. While audio files are smaller than video files by far, it’s reasonable to anticipate a continued upward trajectory for audio assets across the media and entertainment landscape.
2024 Trend: The Shift to Cloud Storage for Cost-Effective Storage and Collaboration
According to Backlight iconik’s 2024 Media Stats Report, the trend toward cloud storage is definitely on the rise as the increased competition in the market and move away from hyperscalers drive more reasonable pricing. Companies are opting to transition to the cloud at their own speed, and hybrid cloud setups give them the freedom to shift assets as needed to improve things like performance, ease of access, security, and meeting regulatory requirements.
Get Ahead of the Wave: Pair iconik With Modern Cloud Storage Today
The reasons so many media professionals are moving to cloud are relatively simple: Cloud workflows enable enhanced collaboration and flexibility, greater cost predictability, and heightened security and management capabilities. And often, all of the above is possible at a lower total cost than legacy solutions.
Pairing Backlight iconik and Backblaze provides a simple solution for users to manage, collaborate, and store media projects easily. By integrating with iconik, Backblaze boosts workflow effectiveness, delivering a strong cloud-based MAM system that allows thorough management of Backblaze B2 Cloud Storage data right from a web browser.
Customer Story: How One Streaming Company Tackled Remote Content Workflows With Backblaze and Backlight iconik
When Goalcast, the empowering media company, decided to dive into making their own content, they realized their current setup just wasn’t cutting it. With their team spread out all over the place, they needed an easy way to get footage, access videos from anywhere, and keep a stash of finished files ready to jazz up for YouTube, Facebook, Instagram, Snapchat, TikTok, and the Goalcast OTT app.
Goalcast combined LucidLink’s cloud-based workflows, iconik’s media asset manager and uploader features, and Backblaze B2 Cloud Storage. The integration between iconik, LucidLink, and Backblaze creates a slick media workflow. The content crew uploads raw footage straight into iconik, tossing in key details. Original files zip into Goalcast’s Backblaze B2 Bucket automatically, while edited versions are up for grabs via LucidLink. After the editing magic, final assets kick back into Backblaze B2.
The integration and partnership means endless possibilities for Goalcast. They’re saving around 150 hours a month in grunt work and stress. Now, they don’t have to fret about where footage hides or how to snag it—it’s all securely stored in Backblaze, ready for anyone on the team to grab, no matter where they’re working from.
You can get lost in the weeds of tech companies and storage solutions. It can hurt your brain. The sweet spot is these three—iconik, LucidLink, and Backblaze—and how they work together.
—Dan Schiffmacher, Production Operations Manager, Goalcast
2024 Media Mega Trend
Looking at Backlight iconik’s numbers and forecasts from a 25,000 foot vantage point makes one thing painfully clear: Effective media management and storage are going to be absolutely crucial for media teams to succeed in the future landscape of production. Dive deeper into how Backblaze and Backlight iconik can support you now and down the road, ensuring seamless media management, and affordable storage, that creates easy, stress-free expansion as your data continues to grow.
Already have iconik and want to get started with Backblaze? Click here.
Account reconciliation is an important step to ensure the completeness and accuracy of financial statements. Specifically, companies must reconcile balance sheet accounts that could contain significant or material misstatements. Accountants go through each account in the general ledger of accounts and verify that the balance listed is complete and accurate. When discrepancies are found, accountants investigate and take appropriate corrective action.
As part of Amazon’s FinTech organization, we offer a software platform that empowers the internal accounting teams at Amazon to conduct account reconciliations. To optimize the reconciliation process, these users require high performance transformation with the ability to scale on demand, as well as the ability to process variable file sizes ranging from as low as a few MBs to more than 100 GB. It’s not always possible to fit data onto a single machine or process it with one single program in a reasonable time frame. This computation has to be done fast enough to provide practical services where programming logic and underlying details (data distribution, fault tolerance, and scheduling) can be separated.
We can achieve these simultaneous computations on multiple machines or threads of the same function across groups of elements of a dataset by using distributed data processing solutions. This encouraged us to reinvent our reconciliation service powered by AWS services, including Amazon EMR and the Apache Spark distributed processing framework, which uses PySpark. This service enables users to process files over 100 GB containing up to 100 million transactions in less than 30 minutes. The reconciliation service has become a powerhouse for data processing, and now users can seamlessly perform a variety of operations, such as Pivot, JOIN (like an Excel VLOOKUP operation), arithmetic operations, and more, providing a versatile and efficient solution for reconciling vast datasets. This enhancement is a testament to the scalability and speed achieved through the adoption of distributed data processing solutions.
In this post, we explain how we integrated Amazon EMR to build a highly available and scalable system that enabled us to run a high-volume financial reconciliation process.
Architecture before migration
The following diagram illustrates our previous architecture.
Our legacy service was built with Amazon Elastic Container Service (Amazon ECS) on AWS Fargate. We processed the data sequentially using Python. However, due to its lack of parallel processing capability, we frequently had to increase the cluster size vertically to support larger datasets. For context, 5 GB of data with 50 operations took around 3 hours to process. This service was configured to scale horizontally to five ECS instances that polled messages from Amazon Simple Queue Service (Amazon SQS), which fed the transformation requests. Each instance was configured with 4 vCPUs and 30 GB of memory to allow horizontal scaling. However, we couldn’t expand its capacity on performance because the process happened sequentially, picking chunks of data from Amazon Simple Storage Service (Amazon S3) for processing. For example, a VLOOKUP operation where two files are to be joined required both files to be read in memory chunk by chunk to obtain the output. This became an obstacle for users because they had to wait for long periods of time to process their datasets.
As part of our re-architecture and modernization, we wanted to achieve the following:
High availability – The data processing clusters should be highly available, providing three 9s of availability (99.9%)
Throughput – The service should handle 1,500 runs per day
Latency – It should be able to process 100 GB of data within 30 minutes
Heterogeneity – The cluster should be able to support a wide variety of workloads, with files ranging from a few MBs to hundreds of GBs
Query concurrency – The implementation demands the ability to support a minimum of 10 degrees of concurrency
Reliability of jobs and data consistency – Jobs need to run reliably and consistently to avoid breaking Service Level Agreements (SLAs)
Cost-effective and scalable – It must be scalable based on the workload, making it cost-effective
Security and compliance – Given the sensitivity of data, it must support fine-grained access control and appropriate security implementations
Monitoring – The solution must offer end-to-end monitoring of the clusters and jobs
Why Amazon EMR
Amazon EMR is the industry-leading cloud big data solution for petabyte-scale data processing, interactive analytics, and machine learning (ML) using open source frameworks such as Apache Spark, Apache Hive, and Presto. With these frameworks and related open-source projects, you can process data for analytics purposes and BI workloads. Amazon EMR lets you transform and move large amounts of data in and out of other AWS data stores and databases, such as Amazon S3 and Amazon DynamoDB.
A notable advantage of Amazon EMR lies in its effective use of parallel processing with PySpark, marking a significant improvement over traditional sequential Python code. This innovative approach streamlines the deployment and scaling of Apache Spark clusters, allowing for efficient parallelization on large datasets. The distributed computing infrastructure not only enhances performance, but also enables the processing of vast amounts of data at unprecedented speeds. Equipped with libraries, PySpark facilitates Excel-like operations on DataFrames, and the higher-level abstraction of DataFrames simplifies intricate data manipulations, reducing code complexity. Combined with automatic cluster provisioning, dynamic resource allocation, and integration with other AWS services, Amazon EMR proves to be a versatile solution suitable for diverse workloads, ranging from batch processing to ML. The inherent fault tolerance in PySpark and Amazon EMR promotes robustness, even in the event of node failures, making it a scalable, cost-effective, and high-performance choice for parallel data processing on AWS.
Amazon EMR extends its capabilities beyond the basics, offering a variety of deployment options to cater to diverse needs. Whether it’s Amazon EMR on EC2, Amazon EMR on EKS, Amazon EMR Serverless, or Amazon EMR on AWS Outposts, you can tailor your approach to specific requirements. For those seeking a serverless environment for Spark jobs, integrating AWS Glue is also a viable option. In addition to supporting various open-source frameworks, including Spark, Amazon EMR provides flexibility in choosing deployment modes, Amazon Elastic Compute Cloud (Amazon EC2) instance types, scaling mechanisms, and numerous cost-saving optimization techniques.
Amazon EMR stands as a dynamic force in the cloud, delivering unmatched capabilities for organizations seeking robust big data solutions. Its seamless integration, powerful features, and adaptability make it an indispensable tool for navigating the complexities of data analytics and ML on AWS.
Redesigned architecture
The following diagram illustrates our redesigned architecture.
The solution operates under an API contract, where clients can submit transformation configurations, defining the set of operations alongside the S3 dataset location for processing. The request is queued through Amazon SQS, then directed to Amazon EMR via a Lambda function. This process initiates the creation of an Amazon EMR step for Spark framework implementation on a dedicated EMR cluster. Although Amazon EMR accommodates an unlimited number of steps over a long-running cluster’s lifetime, only 256 steps can be running or pending simultaneously. For optimal parallelization, the step concurrency is set at 10, allowing 10 steps to run concurrently. In case of request failures, the Amazon SQS dead-letter queue (DLQ) retains the event. Spark processes the request, translating Excel-like operations into PySpark code for an efficient query plan. Resilient DataFrames store input, output, and intermediate data in-memory, optimizing processing speed, reducing disk I/O cost, enhancing workload performance, and delivering the final output to the specified Amazon S3 location.
We define our SLA in two dimensions: latency and throughput. Latency is defined as the amount of time taken to perform one job against a deterministic dataset size and the number of operations performed on the dataset. Throughput is defined as the maximum number of simultaneous jobs the service can perform without breaching the latency SLA of one job. The overall scalability SLA of the service depends on the balance of horizontal scaling of elastic compute resources and vertical scaling of individual servers.
Because we had to run 1,500 processes per day with minimal latency and high performance, we choose to integrate Amazon EMR on EC2 deployment mode with managed scaling enabled to support processing variable file sizes.
The EMR cluster configuration provides many different selections:
The following code provides a snapshot of our cluster configuration:
Concurrent steps:10
EMR Managed Scaling:
minimumCapacityUnits: 64
maximumCapacityUnits: 512
maximumOnDemandCapacityUnits: 512
maximumCoreCapacityUnits: 512
Master Instance Fleet:
r6g.xlarge
- 4 vCore, 30.5 GiB memory, EBS only storage
- EBS Storage:250 GiB
- Maximum Spot price: 100 % of On-demand price
- Each instance counts as 1 units
r6g.2xlarge
- 8 vCore, 61 GiB memory, EBS only storage
- EBS Storage:250 GiB
- Maximum Spot price: 100 % of On-demand price
- Each instance counts as 1 units
Core Instance Fleet:
r6g.2xlarge
- 8 vCore, 61 GiB memory, EBS only storage
- EBS Storage:100 GiB
- Maximum Spot price: 100 % of On-demand price
- Each instance counts as 8 units
r6g.4xlarge
- 16 vCore, 122 GiB memory, EBS only storage
- EBS Storage:100 GiB
- Maximum Spot price: 100 % of On-demand price
- Each instance counts as 16 units
Task Instances:
r6g.2xlarge
- 8 vCore, 61 GiB memory, EBS only storage
- EBS Storage:100 GiB
- Maximum Spot price: 100 % of On-demand price
- Each instance counts as 8 units
r6g.4xlarge
- 16 vCore, 122 GiB memory, EBS only storage
- EBS Storage:100 GiB
- Maximum Spot price: 100 % of On-demand price
- Each instance counts as 16 units
Performance
With our migration to Amazon EMR, we were able to achieve a system performance capable of handling a variety of datasets, ranging from as low as 273 B to as high as 88.5 GB with a p99 of 491 seconds (approximately 8 minutes).
The following figure illustrates the variety of file sizes processed.
The following figure shows our latency.
To compare against sequential processing, we took two datasets containing 53 million records and ran a VLOOKUP operation against each other, along with 49 other Excel-like operations. This took 26 minutes to process in the new service, compared to 5 days to process in the legacy service. This improvement is almost 300 times greater over the previous architecture in terms of performance.
Considerations
Keep in mind the following when considering this solution:
Right-sizing clusters – Although Amazon EMR is resizable, it’s important to right-size the clusters. Right-sizing mitigates a slow cluster, if undersized, or higher costs, if the cluster is oversized. To anticipate these issues, you can calculate the number and type of nodes that will be needed for the workloads.
Parallel steps – Running steps in parallel allows you to run more advanced workloads, increase cluster resource utilization, and reduce the amount of time taken to complete your workload. The number of steps allowed to run at one time is configurable and can be set when a cluster is launched and any time after the cluster has started. You need to consider and optimize the CPU/memory usage per job when multiple jobs are running in a single shared cluster.
Job-based transient EMR clusters – If applicable, it is recommended to use a job-based transient EMR cluster, which delivers superior isolation, verifying that each task operates within its dedicated environment. This approach optimizes resource utilization, helps prevent interference between jobs, and enhances overall performance and reliability. The transient nature enables efficient scaling, providing a robust and isolated solution for diverse data processing needs.
EMR Serverless – EMR Serverless is the ideal choice if you prefer not to handle the management and operation of clusters. It allows you to effortlessly run applications using open-source frameworks available within EMR Serverless, offering a straightforward and hassle-free experience.
AmazonEMR on EKS – Amazon EMR on EKS offers distinct advantages, such as faster startup times and improved scalability resolving compute capacity challenges—which is particularly beneficial for Graviton and Spot Instance users. The inclusion of a broader range of compute types enhances cost-efficiency, allowing tailored resource allocation. Furthermore, Multi-AZ support provides increased availability. These compelling features provide a robust solution for managing big data workloads with improved performance, cost optimization, and reliability across various computing scenarios.
Conclusion
In this post, we explained how Amazon optimized its high-volume financial reconciliation process with Amazon EMR for higher scalability and performance. If you have a monolithic application that’s dependent on vertical scaling to process additional requests or datasets, then migrating it to a distributed processing framework such as Apache Spark and choosing a managed service such as Amazon EMR for compute may help reduce the runtime to lower your delivery SLA, and also may help reduce the Total Cost of Ownership (TCO).
As we embrace Amazon EMR for this particular use case, we encourage you to explore further possibilities in your data innovation journey. Consider evaluating AWS Glue, along with other dynamic Amazon EMR deployment options such as EMR Serverless or Amazon EMR on EKS, to discover the best AWS service tailored to your unique use case. The future of the data innovation journey holds exciting possibilities and advancements to be explored further.
About the Authors
Jeeshan Khetrapal is a Sr. Software Development Engineer at Amazon, where he develops fintech products based on cloud computing serverless architectures that are responsible for companies’ IT general controls, financial reporting, and controllership for governance, risk, and compliance.
Sakti Mishra is a Principal Solutions Architect at AWS, where he helps customers modernize their data architecture and define their end-to-end data strategy, including data security, accessibility, governance, and more. He is also the author of the book Simplify Big Data Analytics with Amazon EMR. Outside of work, Sakti enjoys learning new technologies, watching movies, and visiting places with family.
Keith Fiske gave a talk
(with
slides) about the state of partitioning — splitting a large
table into smaller tables for performance reasons — in PostgreSQL at SCALE
this year. He spoke about the existing support for partitioning, what work still
needs to be done, and what place existing partitioning tools, like his own pg_partman, still have as PostgreSQL gains more built-in features.
Онзи ден Борисов каза, че преговорният екип на ГЕРБ се е борил за това министър на електронното управление да остане Йоловски. Мисля, че е важно да маркирам този факт, защото поне вече е ясно кой носи отговорност за щетите, нанесени там в последните месеци.
В министерството има общо 9 дирекции, главен секретар и една изпълнителна агенция. За последните 9 месеца са уволнени, помолени да напуснат, принудени да напуснат или преместени: главния секретар, изпълнителния директор на агенцията и директорите на 8 от 9-те дирекции.
И тази своеобразна чистка е само една от многото причини за липсата на резултати. Още в края на есента писах, че нямам очаквания, че политическото ръководство на МЕУ ще се справи със задачите, а напредъкът по управленската програма беше основно заради това, което свършихме в парламента. И това е разбираемо – при това разбиване на министерството, няма как там да се работи продуктивно.
Политиката за електронно управление е изключително важна за цялостното развитие на страната – за намаляване на административната тежест, за повече проследимост и прозрачност, за киберсигурността. И има нужда да бъдат придвижвани напред компетентно и систематично – нещо, което в последните 9 месеца се случваше в парламента, но далеч не толкова в МЕУ.
Version 4.10.0 of the Samba Windows interoperability suite has been
released. Changes include better support for group-managed service
accounts, an experimental Windows search protocol client, support for
conditional access control entries, and more.
Security updates have been issued by Fedora (perl-Data-UUID, python-pygments, and thunderbird), Mageia (clojure, grub2, kernel,kmod-xtables-addons,kmod-virtualbox, kernel-linus, nss firefox, nss, python3, python, tcpreplay, and thunderbird), Oracle (nodejs:18), Red Hat (.NET 6.0 and dnsmasq), SUSE (avahi and python39), and Ubuntu (curl, linux-intel-iotg, linux-intel-iotg-5.15, unixodbc, and util-linux).
На 17-ти март Мария Габриел предложи: ротация на премиера и вицепремиера, без смяна на министри, и отлагане на подписването на споразумение за неопределено време.
ППДБ отказахме, защото за нас споразумението беше ключово.
На 19-ти март Мария Габриел внесе несъгласуван състав на Министерския съвет на втория ден от седемте за изпълнение на мандата без логично обяснение защо.
На 24-ти март Николай Денков предложи ротация на премиера и вицепремиера, без смяна на министри, но с подписано споразумение.
ГЕРБ отказаха. Вчера отказаха и повторно аналогично предложение с втория мандат, но с номиниран от тях премиер.
Разликата между предложенията на двете страни е ясна – споразумението. А какво има в него?
Съдебна реформа, реформа на службите, избор на независими регулатори, избор на органи на съдебната власт без гарантирани места за никого.
Все неща, без които държавата не може да върви напред. Неща, които щяха да бъдат протакани, отлагани и подменяни, ако ги няма черно на бяло.
И затова отиваме на избори – защото изглежда ГЕРБ са решили, че предпочитат избори пред това да имат твърд ангажимент по тези реформи, а ние (противно на обвиненията) не искаме да стоим във властта самоцелно, без да правим тези фундаментални за страната промени.
А всички „лакърдии“ от преговорния процес са шум и отклоняване на вниманието – кой с кого се срещал, какви имена задраскал, кой какво поискал, кой колко бил обиден и т.н.
България може да реши фундаменталните си проблеми само с независима съдебна система (без политици да назначават хора по върховете ѝ), с независими регулатори и с работещи служби. И това е най-трудната, но и най-важната политическа задача.
One of the Raspberry Pi Foundation’s core values is our focus on impact. This means that we are committed to learning from the best available evidence, and to being rigorous and transparent about the difference we’re making.
Like many charities, an important part of our approach to achieving and measuring our impact is our theory of change. We are excited to launch a newly refreshed theory of change that reflects our mission and strategy to ensure that young people can realise their full potential through the power of computing and digital technologies.
A theory of change describes the difference an organisation aims to make in the world, the actions it takes to achieve this, and the underlying assumptions about how its actions will create change.
It’s like a good cake recipe. It describes the ingredients and tools that are required, how these are combined, and what the results should be. But a theory of change goes further: it also addresses why you need the cake in the first place, and the reasons why the recipe will produce such a good cake if you follow it correctly!
What is the change we want to make?
Our theory of change begins with a statement of the problem that needs solving: too many young people are missing out on the enormous opportunities from digital technologies, and access to opportunities to learn depends too much on who you are and where you were born.
We want to see a world where young people can take advantage of the opportunities that computers and digital technologies offer to transform their own lives and communities, to contribute to society, and to help address the world’s challenges.
To help us empower young people to do this, we have identified three broad sets of outcomes that we should target, measure, and hold ourselves accountable for. These map roughly to the COM-B model of behaviour change. This model suggests that for change to be achieved, people need a combination of capabilities, opportunities, and motivation.
Our identified outcomes are that we support young people to:
Build knowledge and skills in computing
Understand the opportunities and risks associated with new technologies
Develop the mindsets to confidently engage with technological change
We also support teachers, youth workers, volunteers, and parents to develop their skills and knowledge, and equip them to inspire young people and help them learn. For example, The Computing Curriculum provides a complete bank of free lesson plans and other resources, and Experience AI is our educational programme that includes everything teachers need to deliver lessons on artificial intelligence and machine learning in secondary schools.
Finally, we aim to elevate the state of computing education globally by advocating for policy and systems change, and undertaking our own original research to deepen our understanding of how young people learn about computing.
How will we use our theory of change?
Our theory of change is an important part of our approach to evaluating the impact of our resources and programmes, and it informs all our monitoring and evaluation plans. These plans identify the questions we want to answer, key metrics to monitor, and the data sources we use to understand the impact we’re having and to gather feedback to improve our impact in future.
The theory of change also informs a shared outcomes framework that we are applying consistently across all of our products. This framework supports planning and helps keep us focused as we consider new opportunities to further our mission.
A final role our theory of change plays is to help communicate our mission to other stakeholders, and explain how we can work with our partners and communities to achieve change.
You can read our new theory of change here and if you have any questions or feedback on it, please do get in touch.
The threat resides in the chips’ data memory-dependent prefetcher, a hardware optimization that predicts the memory addresses of data that running code is likely to access in the near future. By loading the contents into the CPU cache before it’s actually needed, the DMP, as the feature is abbreviated, reduces latency between the main memory and the CPU, a common bottleneck in modern computing. DMPs are a relatively new phenomenon found only in M-series chips and Intel’s 13th-generation Raptor Lake microarchitecture, although older forms of prefetchers have been common for years.
[…]
The breakthrough of the new research is that it exposes a previously overlooked behavior of DMPs in Apple silicon: Sometimes they confuse memory content, such as key material, with the pointer value that is used to load other data. As a result, the DMP often reads the data and attempts to treat it as an address to perform memory access. This “dereferencing” of “pointers”—meaning the reading of data and leaking it through a side channel—is a flagrant violation of the constant-time paradigm.
[…]
The attack, which the researchers have named GoFetch, uses an application that doesn’t require root access, only the same user privileges needed by most third-party applications installed on a macOS system. M-series chips are divided into what are known as clusters. The M1, for example, has two clusters: one containing four efficiency cores and the other four performance cores. As long as the GoFetch app and the targeted cryptography app are running on the same performance cluster—even when on separate cores within that cluster—GoFetch can mine enough secrets to leak a secret key.
The attack works against both classical encryption algorithms and a newer generation of encryption that has been hardened to withstand anticipated attacks from quantum computers. The GoFetch app requires less than an hour to extract a 2048-bit RSA key and a little over two hours to extract a 2048-bit Diffie-Hellman key. The attack takes 54 minutes to extract the material required to assemble a Kyber-512 key and about 10 hours for a Dilithium-2 key, not counting offline time needed to process the raw data.
The GoFetch app connects to the targeted app and feeds it inputs that it signs or decrypts. As its doing this, it extracts the app secret key that it uses to perform these cryptographic operations. This mechanism means the targeted app need not perform any cryptographic operations on its own during the collection period.
Note that exploiting the vulnerability requires running a malicious app on the target computer. So it could be worse. On the other hand, like many of these hardware side-channel attacks, it’s not possible to patch.
Все се говори за прозрачност и отчетност, но донякъде иронично остават доста мъгляви понятия. Писал съм за това доста през годините, например за фонда за лечение на деца, връзките на лекари с фарма компании и размислите на Радев дали е нужна прозрачност въобще. Тук опивам три малки примера какво се научава и какво можеш да направиш, ако имаш достъп, достъпност и поставени в контекст данни.
Това са все случаи с места в София, покрай които минавам редовно и затова съм се решил да се занимавам. Накрая ще добавя списък с ресурси, които може да ви помогнат да научите повече за средата около себе си. За съжаление, за София конкретно, тъй като във всички останали градове почти липсва информация.
В първия случай става въпрос за общински имот, на който има стар блок. Зад блока има паркинг. Преди няколко години живущите там са решили да преградят достъпа до имота усвоявайки го и създавайки частен паркинг. Слагат и автоматична врата с контролиран достъп. Преди 5 години някой подава сигнал, констатира се нарушение, установява се точно кой го е извършил, но заповедта се прехвърля между район Изгрев и дирекции в общината докато накрая потъва. Сега имат нов сигнал за същото и отговорът от район Изгрев е общо взето „тогава строителен контрол каза, че няма нарушение и оставихме случая“. Обаче, ако някой намери стария сигнал и прочете какво всъщност е написано, открива, че район Изгрев подвеждат и наистина са седели върху установен и документиран от институциите проблем с общинска земя години наред. Сега ДНСК е изискала нова проверка и действия по въпроса и ги чака.
Вторият случай пак е за общински имот. По-точно три, но ще се фокусираме върху най-големия. Този път инвеститор си е построил блок и е заградил съседните общински имоти. Известно време ги използва за строителни отпадъци, но после просто ги подготвя за строеж. На тези имоти незнайно как има одобрен градоустройствен план за жилищно строителство. Липсват документите за това на сайта на общината, но е добре известно, че става дума за общинска частна собственост. Явно е подготвено за продажба при „удобен общински съвет“. Това беше коментирано из групите на квартала и район Изгрев имат сигнал, на който отговориха вчера след двумесечно забавяне. Установили нарушението и нарушителя и му дали срок за доброволно премахване на оградата и освобождаване на имота. Не става ясно какъв е срокът и кога изтича. Малката подробност е, че аналогични сигнали от различни хора от квартала има 18 месеца по-рано. Тогава същите хора от район Изгрев по същия начин открили нарушение и е дали пак срок за същото. Отново не става ясно какъв, но година и половина по-късно не само няма предприети действия, но въпросният инвеститор си е насадил временни декоративни храстчета, които даже пораснаха, за да скрият какво се прави в имота. Има нов сигнал в общината за бездействието на района и непроследяването на собствените им актове.
Третият случай отново е за инвеститор, този път небезизвестен и с топли връзки с ключови хора в общината. В подготовка на нов техен проект, за да няма шанс някой да го оспорва, си осигуриха отделяне на парцел с широчина три метра по протежението на имота. Така се отделиха от „съседите“, които не бяха уведомени за последващите визи и разрешения, както е по закон. Класическа схема. Така си осигуриха разрешение за строителство само в големия парцел. Прекрасно – прецакаха системата. Последваха редица проблеми дори само със започването на строежа. За повечето бяха предупредени от район Изгрев и не бяха санкционирани. Нещо, което не успяха да скрият е, че са започнали строителни дейности и в малкия парцел, т.е. изкопаха основите и изляха стена на подземните гаражи видимо разширявайки ги в рамките на ония „юридически-санитарен“ имот и извън параметрите на проекта. Общината има сигнал, но единственото, което строителен контрол констатира е, че има разрешително за големия парцел. Премълчават дали се отнася до малкия и дали са направили проверка на място. Отново ДНСК ги чака за отговор. Ако ще се спазва буквата на закона, трябва да важи за всеки етап от строителството. Тук проблемът е, че ако не бъде отстранено това нарушение, на практика проектът не би следвало да получи акт 16, освен ако не прибегнат до нелегалните практики с които се свързва името им в медиите. Предвид как е предвиден проекта и какво се строи се очакват още проблеми най-вече свързани със задължителното озеленяване и дълбочина на почвен слой. Всичко това обаче се очаква да мине безпроблемно проверки също както аналогичните в други подобни проекти.
Всяко от тези неща изглежда дребно на пръв поглед, но са всъщност чести нарушения в София и други градове. Масово не се съблюдават изискванията, не се извършват реални проверки или когато е установено нарушение, не се санкционира или проследява отстраняването му от органите на общината. Понякога това заради чадър от ръководството, понякога е заради саботирани дела, но най-често е заради нехайство, липса на прозрачност и проследяване, а и откровена корупция по ниските нива. Това позволява особено на едри строители, за които иначе се предполага, че са им изрядни документите, да правят куп нарушения, включително с цел позволяване на строителство. Това включва подкупи за получаване на становище за пожарна безопасност, ток и вода, „услуги“ и скриване на процедурите по одобрение, както и уреждане на по-добри параметри за строеж и продажба на общинска земя директно от общинския съвет.
Лесно е да се каже, че в общината са некадърни и „не е виновен тоя дето яде баницата“. В действителност това е модел на поведение, който не се оправя с избори, а с ежедневни усилия, както всяко друго нещо в държавата ни. Означава и че действията на чиновници и техните ръководители също се диктува от това какво може да им се размине. Затова, ако искате да направите нещо отвъд гневните емоджита и писане по групи във фейса, ето няколко ресурса, от които да започнете без да ви отнема много време:
isofmap.bg – това е карта с повечето слоеве на градско планиране и застрояване, които самата община гледа. Там ще намерите информация за собственост на имоти, инфраструктура и прочие. От слоевете ще намерите и карта на планирано и съществуващо застрояване. Отчасти на данните в тази карта се базира 3D картата, която започнах
Регистрите на НАГ – тук има документи за всякакви фази и аспекти от строителството. Включително разрешения за поставяне и санкции.
Картата на НАГ – всеки документ от онзи регистър би трябвало да е на тази карта. Подобно на isofmap има доста слоеве, но като натиснете на имот и показва известни свързани документи. За съжаление, 30% от документите не са свързани с картата, но доста от новите са
call.sofia.bg – сигнали към общината за нередности и проблеми в градската среда.
Визуализацията към call.sofia – тъй като на портала на общината не се откриват стари сигнал и не е особено лесен за търсене по принцип, направих тази визуализация. С нея открих и стаите сигнали, за които говоря по-горе. Пак на база тези данни направих карта на сигналите за паднали клони в София тази зима.
Картата на GovAlert – тъй като регистрите и дори картата на НАГ не са особено лесни за търсене и ориентиране, направих тази карта, която се обновява в реално време. Има филтри за време и видове документи. Също се опитва да свърже документи, които не са включени в картата на НАГ като търси идентификатори на имоти. Повече ще прочетете в статията ми когато започнах проекта преди три години.
Twitter акаунта на @NAG_SO_public – тъй като не всички документи може да се сложат на карта, всичко се пуска допълнително и в този акаунт като новини. Добавени са също прес съобщения от НАГ, обявления за обществени обсъждания и прочие.
Сигурно електронно връчване – за всякаква комуникация с институции е полезно. Трябва само ПИК на НАП или електронен подпис в момента. Докато при сигналите към общината няма опция за отговор или ескалиране на проблем, тук може лесно да се препращат сигнали, добавя информация и оспорват резултати. Също да се изпраща запитвания по ЗДОИ. С този портал няма опция да не входират документ, защото всичко е проследимо и подписано електронно.
Ресурсите за градоустройство в София всъщност предоставят някаква прозрачност и данни, макар да е все още трудна за следене и преглеждане. В другите градове дори това липсва. Доколкото строителството там беше несравнимо по-малко дори спрямо населението и размерите на града, това се променя в последните години особено в Пловдив и Бургас. Затова добавих Пловдив и Благоевград и работя все още да добавя Бургас и Варна към картата и бюлетина на отделен twitter акаунт – @BGCityPlanning. Все пак, поради значително по-малкия поток от информация, може да следите протоколите и обявите на сайта на общината си докато нещо по-добро е налично.
Мария Шаркова е адвокат, специализиращ в сферата на медицинското право. През 2019 г. създава уебсайта „Лекарска грешка“, в който събира статистика за делата по случаите, наречени в правото „медицински деликти“. Тя обаче смята, че в крайна сметка важното е не да се регистрират т.нар. лекарски грешки, а дали може да не се стига до подобни събития. В последното си изследване адв. Шаркова се занимава с въпроса как е гарантирано качеството на медицинската помощ в българската нормативна уредба.
Защо се занимавате с изследвания, свързани с качеството на медицинската помощ?
През 2016 г. учих в САЩ и времето, което изкарах там, ми даде да разбера, че в България не събираме никакви данни, свързани с инцидентите в лечебните заведения и въобще с качеството на медицинската помощ. А когато липсват данни, не може да се вземат аргументирани решения, всичко е само лично мнение.
Когато се върнах, започнах да изследвам съдебната практика при делата на пациенти срещу лекари и лечебни заведения. Правя това и до ден днешен. Натрупах богата база данни от близо 600 дела. Това са хиляди постановени съдебни актове, защото по едно дело може да се постановят и три съдебни акта, ако делото мине на три инстанции. Първият етап беше да извадя ясните количествени индикатори – колко дела са се водили за определен период, кои специалности стават най-често обект на съдебни дела, каква част от тези дела са приключили в полза на пациента и т.н.
Следващият етап дойде логично с въпросите какво е качествена медицинска помощ, кога пациентът получава некачествена медицинска помощ и респективно каква е дължимата грижа, която пациентите имат право да очакват от медицинския персонал и от лечебното заведение. Това не са абстрактни въпроси, те би трябвало да имат ясен отговор в нормативната уредба и в съдебната практика.
Установихте ли такъв ясен отговор при изследването си?
За съжаление, установих, че има много неясноти и много противоречия – както в съдебната практика, така и в правната теория, а и сред самите медицински специалисти. Има много неизяснени въпроси или недокрай изяснени, или такива, които са регламентирани противоречиво.
Наскоро публикувахте статия по този въпрос в сп. „Медицинско право и здравеопазване“ (бр. 1/2024), но читателите на „Тоест“ са с разнообразни компетентности и вероятно малцина от тях са юристи. След като Вие като юрист откривате толкова неясноти, може ли да се формулира достъпен съвет какво има право да изисква всеки от нас като пациент?
Това, което е ясно и което е написано в закона, е, че медицинската помощ в България трябва да се оказва въз основата на утвърдени от науката и практиката методи. Тоест когато пациент отиде в лечебно заведение, той има право да очаква, а медицинският персонал е длъжен да му оказва такава медицинска помощ, която е утвърдена и в медицинската теория, и в практиката.
И тук вече идва въпросът какво означава това. Как разбираме къде е записано по какъв начин се утвърждават тези методи?
Ще Ви дам един добре познат пример. Представете си, че една жена отива да ражда. Допустимо ли е по време на раждането да ѝ приложат метода „Кристелер“, който българските родилки познават като „скачане по корема“ и е описан в учебник по акушерство и гинекология от 1967 г., или медиците, асистиращи на раждането, трябва да се съобразяват със съвременната наука, според която този метод е отречен и се смята за опасен, а в много държави е и изрично забранен? Българската уредба не ни дава ясен отговор.
Друг проблем, който е свързан с оказването на медицинска помощ, е в случаите, в които пациентът смята, че има някакъв пропуск в неговото лечение. За да се установи дали това е така, съдът назначава вещи лица. Когато едно вещо лице преценява дали лечението е било правилно, или дали диагнозата е била правилно поставена, или дали се е процедирало както трябва, то обикновено изразява своето мнение, основано на собствения му опит. Много рядко вещите лица се опират на утвърдените от науката и практиката методи. В доста случаи те дори не посочват научните източници, на които основават твърдението си, че пациентът е получил качествена или некачествена медицинска помощ.
Така че – да се върна към въпроса Ви – всеки от нас има право да изисква и да получи медицинска помощ съобразно утвърдените от науката и практиката методи. За съжаление, никой от нас не може със сигурност да знае кои са тези методи, защото това не е изрично разписано.
В Закона за здравето е записано, че качеството на медицинската помощ се основава на медицински стандарти и Правила за добра медицинска практика. Не следва ли именно в тези документи да пише кои са утвърдените от науката и практиката методи, за които говорите?
По принцип следва. Но тук идва следващият проблем. В Закона за лечебните заведения пише, че тези медицински стандарти трябва да се приемат и утвърждават от министъра на здравеопазването. Но няма единен модел, по който те да бъдат разработвани, не е изяснено какво трябва да е тяхното съдържание, и не е регламентиран редът, по който се изготвят проектите на тези стандарти, докато стигнат до утвърждаване с наредба от министъра на здравеопазването. Така стигаме до съществуващата практика голяма част от стандартите да се изготвят на тъмно, без широкото участие на медицинската общност. Понякога в тях може да се открият лобистки текстове, които отразяват интересите на много тесен кръг от специалисти, участвали в изготвянето им.
Може ли да дадете пример? Трудно е да си представи човек как един медицински стандарт може да обслужва нечий интерес.
Например преди две-три години с промени във всички медицински стандарти беше премахнато изискването за брой медицински персонал, който задължително трябва да има в едно звено, било то клиника или отделение. Това беше оставено на преценката на лечебните заведения в зависимост от тяхната натовареност и необходимост с оглед конкретен пациент. Но това е едно много широко понятие, а броят на персонала много често има пряко отношение към качеството на медицинската помощ. Ако в една клиника или отделение има 30 или 35 пациенти, не е редно да се остави на преценката на лечебното заведение дали те ще бъдат обслужвани от петима специалисти, или от един специализант.
Извън тези количествени показатели не са ли разписани в медицинските стандарти конкретни „методи, утвърдени в науката и практиката“?
Най-често не са. Иначе казано, в момента пациентите в България по закон имат право да получат качествена медицинска помощ, но ако по някаква причина сметнат, че това тяхно право е нарушено, няма как да го докажат. Това ще зависи от субективната преценка на вещите лица.
Да се върнем към примера ни за метода „Кристелер“. Ако родилката, която споменахме по-рано в разговора, прецени, че като са ѝ приложили този метод, това не отговаря на изискването за качествена медицинска помощ, защото например ѝ е руптурирала матката или са ѝ счупили две ребра, или има други травми, тя трябва да докаже дали този метод е утвърден в науката и практиката, или не. Но в едно съдебно дело отговорът на въпроса ще зависи изцяло от вещото лице. И ако вещото лице е спряло своето професионално развитие с учебника от 1967 г., ще отговори, че да, това е един възможен метод, утвърден, и няма нищо лошо в използването му.
Както пациентът зависи от това дали дадено вещо лице е актуализирало познанията си, по същия начин при евентуален правен спор зависи и медицинският специалист. Попадала съм на становище на вещо лице, в което пише, че в медицината всичко е възможно. Попадала съм на становище, в което лабораторните изследвания са сравнени с „невярна любовница“.
Когато говорим за тези утвърдени от науката и практиката методи, те най-често се описват в документи, наречени протоколи или алгоритми за клинично поведение. В тях се описват действията, които трябва да се извършат в конкретна клинична ситуация, защото пациентът по принцип има право на „своевременна и достатъчна“ медицинска помощ, но за всяка конкретна ситуация кое е своевременно и кое е достатъчно, се описва именно в тези протоколи. В голяма част от медицинските стандарти обаче не се говори въобще за протоколи и алгоритми за поведение. В други се насочва към протоколите на конкретно професионално дружество, без да е ясно защо се реферира към тях. В трети се изисква всяко лечебно заведение само̀ да си изработи такива протоколи, а по някои специалности въобще няма разписани стандарти. Това създава един водовъртеж от случайни обстоятелства, в центъра на които попада пациентът.
Има ли добър пример?
Спешната медицина е единствената сфера, в която има утвърдени със заповед на министъра на здравеопазването правила за клинично поведение. Това е така, защото е предвидено и в самия стандарт.
Разговорът ни не звучи оптимистично дотук. Излиза, че като пациенти не сме особено защитени и разчитаме изцяло на личностните качества на медицинските специалисти, при които ще попаднем.
Напомняте ми да отбележа, че медицинските специалисти също не са добре защитени. Защото и те разчитат на личностните си качества и ако при тях попадне случай, който надхвърля компетенциите им, те са в риск, защото няма начертана система, която да ги подкрепи.
Нещо повече. Нормативната уредба нерядко, вместо да ги насърчава и подкрепя да прилагат медицина, основана на доказателства, в някои случаи изисква от тях точно обратното. Защото алгоритъмът, към който те са длъжни да се придържат, е на клиничната пътека. Ако този алгоритъм не бъде изпълнен, Здравната каса няма да заплати лечението или ще глоби лечебното заведение. А тези алгоритми нямат отношение към медицината, основана на доказателства, и нерядко принуждават лекарите да извършват ненужни дейности, но и не им дават възможност да извършат необходимите. Системата не предполага субективните качества и умения на работещите в нея да бъдат възпитавани в духа на съвременната медицинска наука. И това е голям проблем за всички, не само за пациентите или само за медиците.
Бихте ли обяснили понятието „медицина, основана на доказателства“?
Добрият медицински специалист е този, който прилага утвърдените от науката и практиката методи, но ги прилага чрез позоваване на медицината, основана на доказателства. Това означава, че когато лекарят или медицинската сестра, или акушерката, или друг медицински специалист избира да прилага даден метод, той трябва да бъде актуален и да бъде доказан. В медицинската наука има много ясни правила как един диагностично-лечебен метод се утвърждава и медицинските специалисти трябва да познават тези правила.
Нека се върнем към нашия си пример – ако се чудим дали прилагането на метода „Кристелер“ съответства на качествената медицинска помощ, можем да проверим, следвайки тези правила на медицинската наука. И ще установим как през 1967 г. се е смятало, че това е единственият начин в определени случаи да подпомогнеш раждането при даден проблем. Но през годините са събрани данни, проведени са научни изследвания и проучвания, вече е доказано, че рискът от прилагането на метода надхвърля в пъти повече евентуалните ползи. Затова към момента това не е утвърден от науката и практиката метод.
Как се гарантира на практика дължимата грижа и качеството на медицинската помощ в по-добре регулирани системи?
Нито една система не е съвършена, но има системи, в които за това се мисли активно. Един от ключовите моменти е осигуряването на задължително продължаващо обучение за медицинските специалисти, което да бъде и ефективно, и контролирано. Казано по-просто, държавата трябва да гарантира, че тези хора периодично се обучават в новите достижения на медицинската наука в своята сфера, а след това да контролира как новостите се прилагат в практиката.
Другото е създаването на работещи етични правила и подкрепянето на медицинските специалисти да се придържат към тях. Тук говорим за нещо просто, каквото е очакването на пациента да получи човешко отношение, защото той е уязвимата страна в отношенията с лекаря и защото никой не е станал пациент по желание. Да се създадат условия за такова общуване между медици и пациенти, които да гарантират, че информираното съгласие не е само една бланка, която пациентът подписва под натиск, а истинска комуникация, в която му става ясно какво му предстои.
Третото, за което се мисли, е гарантирането на пътя на пациента през системата. Това са взаимовръзките между различни специалисти, различни лечебни заведения и различни етапи на лечение. Наскоро при мен беше пациентка, диагностицирана със злокачествено заболяване на кръвта. В решението си онкологичната комисия препоръчваше ревизия на хистологичните блокчета, както и извършване на ядрено-магнитен резонанс. Без обаче никой да насочи жената къде да направи този ядрено-магнитен резонанс, по какъв начин да се снабди с хистологията си, къде да бъде осъществена тази ревизия, кой да я осъществи и след като евентуално направи ревизията и ядрено-магнитния резонанс, какво да прави с резултатите. Никаква представа. Това беше забавило лечението на пациентката с около три месеца.
В изследването си стигнахте ли до извод какво може да направи един пациент, за да си осигури качествена медицинска помощ въпреки недостатъците и противоречията в правилата?
За съжаление, смея да кажа, че обективни предпоставки на законодателно равнище, които да гарантират подобна дължима грижа, няма. Това е въпрос на субективните качества на лекарите или на субективните качества на ръководителя на лечебно заведение. Но за да внеса малко оптимизъм, трябва да кажа, че все по-често срещам млади лекари, които искат да работят по съвременен начин, инвестират сами в развитието си и се опитват да бъдат коректив на системните грешки. В повечето случаи и в повечето лечебни заведения наистина се полага старание да се оказва оптималната медицинска помощ, която всеки пациент заслужава да получи и има право да получи.
As the Chief Information Security Officer (CISO) at AWS, I’m personally committed to helping security teams of all skill levels and sizes navigate security for generative artificial intelligence (AI). As a former AWS customer, I know the value of hands-on security learning and talking in-person to the people who build and run AWS security. That’s why I’m excited for you to join me at AWS re:Inforce 2024, our annual cloud security event, where you can collaborate with experts, partners, and the builders who are driving the future of security in the generative AI era.
Whether you want to build deep technical expertise, understand how to prioritize your security investments, or learn how to apply foundational security best practices, re:Inforce is a great opportunity to dive deep into the convergence of security and AI. AI and machine learning (ML) have been a focus for Amazon for more than 25 years. It’s inspiring to take advantage of and adapt to the impact generative AI is having on the world.
AWS re:Inforce isn’t just a conference—it’s a catalyst for innovation and collaboration in the realm of cloud security. This year, we’re coming together June 10–12 in Pennsylvania for 2.5 days of immersive cloud security learning designed to help drive your business initiatives. At AWS, we’ve always believed that security is a business enabler. Security reduces risk, reinforces resilience, and empowers confident innovation. Security helps organizations use new technologies such as generative AI quickly and safely, creating better experiences for customers, partners, and employees.
Here’s a bit of what you can expect:
How we secure AWS today and my vision for the future AWS re:Inforce 2024 will begin with my keynote on Tuesday, June 11, 2024 at 9:00 AM EST. By the time re:Inforce comes around, I will have been the CISO of AWS for nearly a year. It’s incredible to think about all the innovations that have happened within AWS Security during that time. You’ll hear about these innovations, what we learned from them, and how we use them to secure AWS. I’ll also share my vision for the future of AWS Security. Steve Schmidt, CSO of Amazon, will take the stage to share his thoughts on how a strong culture of security supports the safe use of generative AI.
Navigate security for generative AI and other emerging trends Now is the time for security teams to empower their builders to confidently innovate with generative AI. Be the first to hear about the latest AWS security advances around generative AI and have access to interactive sessions where you can learn how to implement AI workloads securely, explore use cases from other customers, and see demos from AWS and our partners of AI-driven security in action. Be sure to check out our Innovation Talks, where AWS security experts will give in-depth talks on essential topics including cryptography, generative AI, and building a culture of security.
This year, we’ve extended the event by half a day to give you more learning opportunities. At re:Inforce, you can personalize your agenda by choosing from more than 250 different sessions spanning data protection; identity and access management; threat detection and incident response; network and infrastructure security; governance, risk, and compliance; and application security. And we have an inspiring line-up of customer speakers this year who will share their firsthand experience innovating securely on AWS. More than 90 of our trusted security partners will also be there to help you simplify and integrate your security portfolio, and those of you looking to deepen security expertise will find more than 70 percent of re:Inforce sessions are advanced or expert level.
Take advantage of the latest innovations in AWS security You’ll hear about our latest announcements and product launches and learn how to operationalize these security innovations in over 100 interactive-format sessions. In response to customer feedback, we’ve added more interactive session formats, including chalk talks, code talks, workshops, and builders’ sessions. Don’t miss this chance to connect directly with AWS experts to learn how you can get more out of the security tools you already have.
Connect with AWS experts, partners, and your peers The opportunity to come together with other members of the security community is something that really energizes me. Coming together in person gives us all the opportunity to connect with peers, find mentors, and learn from each other. You can advance your career development goals with attendee-matchmaking tools, explore the Expo to connect with trusted partners, and join lounges and activities designed for specific interest groups in the security community.
Meet up with AWS Security Heroes, security professionals, IT leaders, educators, and developers with a shared mission to foster excellence in the practice and profession of cybersecurity and digital identity. Or, connect with members of the AWS Community Builders program, AWS technical enthusiasts and emerging thought leaders who are passionate about sharing knowledge and connecting with the security community. There’s no better opportunity to make new connections with the diverse AWS security community.
Register today with the code SECBLOfnakb to receive a limited time $150 USD discount, while supplies last.
If you’re in the first five years of your cloud security career, you might qualify for the All Builders Welcome Grant. This grant removes the financial barrier to attend AWS re:Inforce for underrepresented technologists as part of our commitment to creating a cybersecurity community that is inclusive, diverse, and equitable.
Generative artificial intelligence (AI) has captured the imagination of organizations and individuals around the world, and many have already adopted it to help improve workforce productivity, transform customer experiences, and more.
When you use a generative AI-based service, you should understand how the information that you enter into the application is stored, processed, shared, and used by the model provider or the provider of the environment that the model runs in. Organizations that offer generative AI solutions have a responsibility to their users and consumers to build appropriate safeguards, designed to help verify privacy, compliance, and security in their applications and in how they use and train their models.
This post continues our series on how to secure generative AI, and provides guidance on the regulatory, privacy, and compliance challenges of deploying and building generative AI workloads. We recommend that you start by reading the first post of this series: Securing generative AI: An introduction to the Generative AI Security Scoping Matrix, which introduces you to the Generative AI Scoping Matrix—a tool to help you identify your generative AI use case—and lays the foundation for the rest of our series.
Figure 1 shows the scoping matrix:
Figure 1: Generative AI Scoping Matrix
Broadly speaking, we can classify the use cases in the scoping matrix into two categories: prebuilt generative AI applications (Scopes 1 and 2), and self-built generative AI applications (Scopes 3–5). Although some consistent legal, governance, and compliance requirements apply to all five scopes, each scope also has unique requirements and considerations. We will cover some key considerations and best practices for each scope.
Scope 1: Consumer applications
Consumer applications are typically aimed at home or non-professional users, and they’re usually accessed through a web browser or a mobile app. Many applications that created the initial excitement around generative AI fall into this scope, and can be free or paid for, using a standard end-user license agreement (EULA). Although they might not be built specifically for enterprise use, these applications have widespread popularity. Your employees might be using them for their own personal use and might expect to have such capabilities to help with work tasks.
Many large organizations consider these applications to be a risk because they can’t control what happens to the data that is input or who has access to it. In response, they ban Scope 1 applications. Although we encourage due diligence in assessing the risks, outright bans can be counterproductive. Banning Scope 1 applications can cause unintended consequences similar to that of shadow IT, such as employees using personal devices to bypass controls that limit use, reducing visibility into the applications that they use. Instead of banning generative AI applications, organizations should consider which, if any, of these applications can be used effectively by the workforce, but within the bounds of what the organization can control, and the data that are permitted for use within them.
To help your workforce understand the risks associated with generative AI and what is acceptable use, you should create a generative AI governance strategy, with specific usage guidelines, and verify your users are made aware of these policies at the right time. For example, you could have a proxy or cloud access security broker (CASB) control that, when accessing a generative AI based service, provides a link to your company’s public generative AI usage policy and a button that requires them to accept the policy each time they access a Scope 1 service through a web browser when using a device that your organization issued and manages. This helps verify that your workforce is trained and understands the risks, and accepts the policy before using such a service.
To help address some key risks associated with Scope 1 applications, prioritize the following considerations:
Identify which generative AI services your staff are currently using and seeking to use.
Understand the service provider’s terms of service and privacy policy for each service, including who has access to the data and what can be done with the data, including prompts and outputs, how the data might be used, and where it’s stored.
Understand the source data used by the model provider to train the model. How do you know the outputs are accurate and relevant to your request? Consider implementing a human-based testing process to help review and validate that the output is accurate and relevant to your use case, and provide mechanisms to gather feedback from users on accuracy and relevance to help improve responses.
Seek legal guidance about the implications of the output received or the use of outputs commercially. Determine who owns the output from a Scope 1 generative AI application, and who is liable if the output uses (for example) private or copyrighted information during inference that is then used to create the output that your organization uses.
The EULA and privacy policy of these applications will change over time with minimal notice. Changes in license terms can result in changes to ownership of outputs, changes to processing and handling of your data, or even liability changes on the use of outputs. Create a plan/strategy/mechanism to monitor the policies on approved generative AI applications. Review the changes and adjust your use of the applications accordingly.
For Scope 1 applications, the best approach is to consider the input prompts and generated content as public, and not to use personally identifiable information (PII), highly sensitive, confidential, proprietary, or company intellectual property (IP) data with these applications.
Scope 1 applications typically offer the fewest options in terms of data residency and jurisdiction, especially if your staff are using them in a free or low-cost price tier. If your organization has strict requirements around the countries where data is stored and the laws that apply to data processing, Scope 1 applications offer the fewest controls, and might not be able to meet your requirements.
Scope 2: Enterprise applications
The main difference between Scope 1 and Scope 2 applications is that Scope 2 applications provide the opportunity to negotiate contractual terms and establish a formal business-to-business (B2B) relationship. They are aimed at organizations for professional use with defined service level agreements (SLAs) and licensing terms and conditions, and they are usually paid for under enterprise agreements or standard business contract terms. The enterprise agreement in place usually limits approved use to specific types (and sensitivities) of data.
Most aspects from Scope 1 apply to Scope 2. However, in Scope 2, you are intentionally using your proprietary data and encouraging the widespread use of the service across your organization. When assessing the risk, consider these additional points:
Determine the acceptable classification of data that is permitted to be used with each Scope 2 application, update your data handling policy to reflect this, and include it in your workforce training.
Understand the data flow of the service. Ask the provider how they process and store your data, prompts, and outputs, who has access to it, and for what purpose. Do they have any certifications or attestations that provide evidence of what they claim and are these aligned with what your organization requires. Make sure that these details are included in the contractual terms and conditions that you or your organization agree to.
What (if any) data residency requirements do you have for the types of data being used with this application? Understand where your data will reside and if this aligns with your legal or regulatory obligations.
Many major generative AI vendors operate in the USA. If you are based outside the USA and you use their services, you have to consider the legal implications and privacy obligations related to data transfers to and from the USA.
Vendors that offer choices in data residency often have specific mechanisms you must use to have your data processed in a specific jurisdiction. You might need to indicate a preference at account creation time, opt into a specific kind of processing after you have created your account, or connect to specific regional endpoints to access their service.
Most Scope 2 providers want to use your data to enhance and train their foundational models. You will probably consent by default when you accept their terms and conditions. Consider whether that use of your data is permissible. If your data is used to train their model, there is a risk that a later, different user of the same service could receive your data in their output. If you need to prevent reuse of your data, find the opt-out options for your provider. You might need to negotiate with them if they don’t have a self-service option for opting out.
When you use an enterprise generative AI tool, your company’s usage of the tool is typically metered by API calls. That is, you pay a certain fee for a certain number of calls to the APIs. Those API calls are authenticated by the API keys the provider issues to you. You need to have strong mechanisms for protecting those API keys and for monitoring their usage. If the API keys are disclosed to unauthorized parties, those parties will be able to make API calls that are billed to you. Usage by those unauthorized parties will also be attributed to your organization, potentially training the model (if you’ve agreed to that) and impacting subsequent uses of the service by polluting the model with irrelevant or malicious data.
Scope 3: Pre-trained models
In contrast to prebuilt applications (Scopes 1 and 2), Scope 3 applications involve building your own generative AI applications by using a pretrained foundation model available through services such as Amazon Bedrock and Amazon SageMaker JumpStart. You can use these solutions for your workforce or external customers. Much of the guidance for Scopes 1 and 2 also applies here; however, there are some additional considerations:
A common feature of model providers is to allow you to provide feedback to them when the outputs don’t match your expectations. Does the model vendor have a feedback mechanism that you can use? If so, make sure that you have a mechanism to remove sensitive content before sending feedback to them.
Does the provider have an indemnification policy in the event of legal challenges for potential copyright content generated that you use commercially, and has there been case precedent around it?
Is your data included in prompts or responses that the model provider uses? If so, for what purpose and in which location, how is it protected, and can you opt out of the provider using it for other purposes, such as training? At Amazon, we don’t use your prompts and outputs to train or improve the underlying models in Amazon Bedrock and SageMaker JumpStart (including those from third parties), and humans won’t review them. Also, we don’t share your data with third-party model providers. Your data remains private to you within your AWS accounts.
Establish a process, guidelines, and tooling for output validation. How do you make sure that the right information is included in the outputs based on your fine-tuned model, and how do you test the model’s accuracy? For example:
If the application is generating text, create a test and output validation process that is tested by humans on a regular basis (for example, once a week) to verify the generated outputs are producing the expected results.
Another approach could be to implement a feedback mechanism that the users of your application can use to submit information on the accuracy and relevance of output.
If generating programming code, this should be scanned and validated in the same way that any other code is checked and validated in your organization.
Scope 4: Fine-tuned models
Scope 4 is an extension of Scope 3, where the model that you use in your application is fine-tuned with data that you provide to improve its responses and be more specific to your needs. The considerations for Scope 3 are also relevant to Scope 4; in addition, you should consider the following:
What is the source of the data used to fine-tune the model? Understand the quality of the source data used for fine-tuning, who owns it, and how that could lead to potential copyright or privacy challenges when used.
Remember that fine-tuned models inherit the data classification of the whole of the data involved, including the data that you use for fine-tuning. If you use sensitive data, then you should restrict access to the model and generated content to that of the classified data.
As a general rule, be careful what data you use to tune the model, because changing your mind will increase cost and delays. If you tune a model on PII directly, and later determine that you need to remove that data from the model, you can’t directly delete data. With current technology, the only way for a model to unlearn data is to completely retrain the model. Retraining usually requires a lot of time and money.
Scope 5: Self-trained models
With Scope 5 applications, you not only build the application, but you also train a model from scratch by using training data that you have collected and have access to. Currently, this is the only approach that provides full information about the body of data that the model uses. The data can be internal organization data, public data, or both. You control many aspects of the training process, and optionally, the fine-tuning process. Depending on the volume of data and the size and complexity of your model, building a scope 5 application requires more expertise, money, and time than any other kind of AI application. Although some customers have a definite need to create Scope 5 applications, we see many builders opting for Scope 3 or 4 solutions.
For Scope 5 applications, here are some items to consider:
You are the model provider and must assume the responsibility to clearly communicate to the model users how the data will be used, stored, and maintained through a EULA.
Unless required by your application, avoid training a model on PII or highly sensitive data directly.
Your trained model is subject to all the same regulatory requirements as the source training data. Govern and protect the training data and trained model according to your regulatory and compliance requirements. After the model is trained, it inherits the data classification of the data that it was trained on.
To limit potential risk of sensitive information disclosure, limit the use and storage of the application users’ data (prompts and outputs) to the minimum needed.
AI regulation and legislation
AI regulations are rapidly evolving and this could impact you and your development of new services that include AI as a component of the workload. At AWS, we’re committed to developing AI responsibly and taking a people-centric approach that prioritizes education, science, and our customers, to integrate responsible AI across the end-to-end AI lifecycle. For more details, see our Responsible AI resources. To help you understand various AI policies and regulations, the OECD AI Policy Observatory is a good starting point for information about AI policy initiatives from around the world that might affect you and your customers. At the time of publication of this post, there are over 1,000 initiatives across more 69 countries.
Our recommendation for AI regulation and legislation is simple: monitor your regulatory environment, and be ready to pivot your project scope if required.
Theme 1: Data privacy
According to the UK Information Commissioners Office (UK ICO), the emergence of generative AI doesn’t change the principles of data privacy laws, or your obligations to uphold them. There are implications when using personal data in generative AI workloads. Personal data might be included in the model when it’s trained, submitted to the AI system as an input, or produced by the AI system as an output. Personal data from inputs and outputs can be used to help make the model more accurate over time via retraining.
For AI projects, many data privacy laws require you to minimize the data being used to what is strictly necessary to get the job done. To go deeper on this topic, you can use the eight questions framework published by the UK ICO as a guide. We recommend using this framework as a mechanism to review your AI project data privacy risks, working with your legal counsel or Data Protection Officer.
In simple terms, follow the maxim “don’t record unnecessary data” in your project.
Theme 2: Transparency and explainability
The OECD AI Observatory defines transparency and explainability in the context of AI workloads. First, it means disclosing when AI is used. For example, if a user interacts with an AI chatbot, tell them that. Second, it means enabling people to understand how the AI system was developed and trained, and how it operates. For example, the UK ICO provides guidance on what documentation and other artifacts you should provide that describe how your AI system works. In general, transparency doesn’t extend to disclosure of proprietary sources, code, or datasets. Explainability means enabling the people affected, and your regulators, to understand how your AI system arrived at the decision that it did. For example, if a user receives an output that they don’t agree with, then they should be able to challenge it.
So what can you do to meet these legal requirements? In practical terms, you might be required to show the regulator that you have documented how you implemented the AI principles throughout the development and operation lifecycle of your AI system. In addition to the ICO guidance, you can also consider implementing an AI Management system based on ISO42001:2023.
Diving deeper on transparency, you might need to be able to show the regulator evidence of how you collected the data, as well as how you trained your model.
Transparency with your data collection process is important to reduce risks associated with data. One of the leading tools to help you manage the transparency of the data collection process in your project is Pushkarna and Zaldivar’s Data Cards (2022) documentation framework. The Data Cards tool provides structured summaries of machine learning (ML) data; it records data sources, data collection methods, training and evaluation methods, intended use, and decisions that affect model performance. If you import datasets from open source or public sources, review the Data Provenance Explorer initiative. This project has audited over 1,800 datasets for licensing, creators, and origin of data.
Transparency with your model creation process is important to reduce risks associated with explainability, governance, and reporting. Amazon SageMaker has a feature called Model Cards that you can use to help document critical details about your ML models in a single place, and streamlining governance and reporting. You should catalog details such as intended use of the model, risk rating, training details and metrics, and evaluation results and observations.
When you use models that were trained outside of your organization, then you will need to rely on Standard Contractual Clauses. SCC’s enable sharing and transfer of any personal information that the model might have been trained on, especially if data is being transferred from the EU to third countries. As part of your due diligence, you should contact the vendor of your model to ask for a Data Card, Model Card, Data Protection Impact Assessment (for example, ISO29134:2023), or Transfer Impact Assessment (for example, IAPP). If no such documentation exists, then you should factor this into your own risk assessment when making a decision to use that model. Two examples of third-party AI providers that have worked to establish transparency for their products are Twilio and SalesForce. Twilio provides AI Nutrition Facts labels for its products to make it simple to understand the data and model. SalesForce addresses this challenge by making changes to their acceptable use policy.
Theme 3: Automated decision making and human oversight
The final draft of the EUAIA, which starts to come into force from 2026, addresses the risk that automated decision making is potentially harmful to data subjects because there is no human intervention or right of appeal with an AI model. Responses from a model have a likelihood of accuracy, so you should consider how to implement human intervention to increase certainty. This is important for workloads that can have serious social and legal consequences for people—for example, models that profile people or make decisions about access to social benefits. We recommend that when you are developing your business case for an AI project, consider where human oversight should be applied in the workflow.
The UK ICO provides guidance on what specific measures you should take in your workload. You might give users information about the processing of the data, introduce simple ways for them to request human intervention or challenge a decision, carry out regular checks to make sure that the systems are working as intended, and give individuals the right to contest a decision.
The US Executive Order for AI describes the need to protect people from automatic discrimination based on sensitive characteristics. The order places the onus on the creators of AI products to take proactive and verifiable steps to help verify that individual rights are protected, and the outputs of these systems are equitable.
Prescriptive guidance on this topic would be to assess the risk classification of your workload and determine points in the workflow where a human operator needs to approve or check a result. Addressing bias in the training data or decision making of AI might include having a policy of treating AI decisions as advisory, and training human operators to recognize those biases and take manual actions as part of the workflow.
Theme 4: Regulatory classification of AI systems
Just like businesses classify data to manage risks, some regulatory frameworks classify AI systems. It is a good idea to become familiar with the classifications that might affect you. The EUAIA uses a pyramid of risks model to classify workload types. If a workload has an unacceptable risk (according to the EUAIA), then it might be banned altogether.
Banned workloads The EUAIA identifies several AI workloads that are banned, including CCTV or mass surveillance systems, systems used for social scoring by public authorities, and workloads that profile users based on sensitive characteristics. We recommend you perform a legal assessment of your workload early in the development lifecycle using the latest information from regulators.
High risk workloads There are also several types of data processing activities that the Data Privacy law considers to be high risk. If you are building workloads in this category then you should expect a higher level of scrutiny by regulators, and you should factor extra resources into your project timeline to meet regulatory requirements. The good news is that the artifacts you created to document transparency, explainability, and your risk assessment or threat model, might help you meet the reporting requirements. To see an example of these artifacts. see the AI and data protection risk toolkit published by the UK ICO.
Examples of high-risk processing include innovative technology such as wearables, autonomous vehicles, or workloads that might deny service to users such as credit checking or insurance quotes. We recommend that you engage your legal counsel early in your AI project to review your workload and advise on which regulatory artifacts need to be created and maintained. You can see further examples of high risk workloads at the UK ICO site here.
The EUAIA also pays particular attention to profiling workloads. The UK ICO defines this as “any form of automated processing of personal data consisting of the use of personal data to evaluate certain personal aspects relating to a natural person, in particular to analyse or predict aspects concerning that natural person’s performance at work, economic situation, health, personal preferences, interests, reliability, behaviour, location or movements.” Our guidance is that you should engage your legal team to perform a review early in your AI projects.
We recommend that you factor a regulatory review into your timeline to help you make a decision about whether your project is within your organization’s risk appetite. We recommend you maintain ongoing monitoring of your legal environment as the laws are rapidly evolving.
Theme 6: Safety
ISO42001:2023 defines safety of AI systems as “systems behaving in expected ways under any circumstances without endangering human life, health, property or the environment.”
The United States AI Bill of Rights states that people have a right to be protected from unsafe or ineffective systems. In October 2023, President Biden issued the Executive Order on Safe, Secure and Trustworthy Artificial Intelligence, which highlights the requirement to understand the context of use for an AI system, engaging the stakeholders in the community that will be affected by its use. The Executive Order also describes the documentation, controls, testing, and independent validation of AI systems, which aligns closely with the explainability theme that we discussed previously. For your workload, make sure that you have met the explainability and transparency requirements so that you have artifacts to show a regulator if concerns about safety arise. The OECD also offers prescriptive guidance here, highlighting the need for traceability in your workload as well as regular, adequate risk assessments—for example, ISO23894:2023 AI Guidance on risk management.
Conclusion
Although generative AI might be a new technology for your organization, many of the existing governance, compliance, and privacy frameworks that we use today in other domains apply to generative AI applications. Data that you use to train generative AI models, prompt inputs, and the outputs from the application should be treated no differently to other data in your environment and should fall within the scope of your existing data governance and data handling policies. Be mindful of the restrictions around personal data, especially if children or vulnerable people can be impacted by your workload. When fine-tuning a model with your own data, review the data that is used and know the classification of the data, how and where it’s stored and protected, who has access to the data and trained models, and which data can be viewed by the end user. Create a program to train users on the uses of generative AI, how it will be used, and data protection policies that they need to adhere to. For data that you obtain from third parties, make a risk assessment of those suppliers and look for Data Cards to help ascertain the provenance of the data.
Regulation and legislation typically take time to formulate and establish; however, existing laws already apply to generative AI, and other laws on AI are evolving to include generative AI. Your legal counsel should help keep you updated on these changes. When you build your own application, you should be aware of new legislation and regulation that is in draft form (such as the EU AI Act) and whether it will affect you, in addition to the many others that might already exist in locations where you operate, because they could restrict or even prohibit your application, depending on the risk the application poses.
At AWS, we make it simpler to realize the business value of generative AI in your organization, so that you can reinvent customer experiences, enhance productivity, and accelerate growth with generative AI. If you want to dive deeper into additional areas of generative AI security, check out the other posts in our Securing Generative AI series:
If you have feedback about this post, submit comments in the Comments section below. If you have questions about this post, start a new thread on the Generative AI on AWS re:Post or contact AWS Support.
Implementing authentication and authorization mechanisms in modern applications can be challenging, especially when dealing with various client types and use cases. As developers, we often struggle to choose the right authentication flow to balance security, user experience, and application requirements. This is where understanding the OAuth 2.0 grant types comes into play. Whether you’re building a traditional web application, a mobile app, or a machine-to-machine communication system, understanding the OAuth 2.0 grant types can help you implement robust and secure authentication and authorization mechanism.
In this blog post, we show you the different OAuth 2.0 grants and how to implement them in Amazon Cognito. We review the purpose of each grant, their relevance in modern application development, and which grant is best suited for different application requirements.
OAuth 2.0 is an authorization framework that enables secure and seamless access to resources on behalf of users without the need to share sensitive credentials. The primary objective of OAuth 2.0 is to establish a secure, delegated, and scoped access mechanism that allows third-party applications to interact with user data while maintaining robust privacy and security measures.
OpenID Connect, often referred to as OIDC, is a protocol based on OAuth 2.0. It extends OAuth 2.0 to provide user authentication, identity verification, and user information retrieval. OIDC is a crucial component for building secure and user-friendly authentication experiences in applications. Amazon Cognito supports OIDC, meaning it supports user authentication and identity verification according to OIDC standards.
Amazon Cognito is an identity environment for web and mobile applications. Its two main components are user pools and identity pools. A Cognito user pool is a user directory, an authentication server, and an authorization service for OAuth 2.0 tokens. With it, you can authenticate and authorize users natively or from a federated identity such as your enterprise directory, or from consumer identity providers such as Google or Facebook. Cognito Identity Pool can exchange OAuth 2.0 tokens (among other options) for AWS credentials.
Implementing OAuth 2.0 grants using Amazon Cognito
The OAuth 2.0 standard defines four main roles; these are important to know as we discuss the grants:
A resource owner owns the data in the resource server and can grant access to the resource (such as a database admin).
A resource server hosts the protected resources that the application wants to access (such as a SQL server).
A client is an application making requests for the protected resources on behalf of the resource owner and with its authorization (such as an analytics application).
An authorization server is a server that issues scoped tokens after the user is authenticated and has consented to the issuance of the token under the desired scope (such as Amazon Cognito).
A few other useful concepts before we dive into the OAuth 2.0 grants:
Access tokens are at the core of OAuth 2.0’s operation. These tokens are short-lived credentials that the client application uses to prove its authorized status when requesting resources from the resource server. Additionally, OAuth 2.0 might involve the use of refresh tokens, which provide a mechanism for clients to obtain new access tokens without requiring the resource owner’s intervention.
An ID token is a JSON Web Token (JWT) introduced by OpenID Connect that contains information about the authentication event of the user. They allow applications to verify the identity of the user, make informed decisions about the user’s authentication status, and personalize the user’s experience.
A scope is a level of access that an application can request to a resource. Scopes define the specific permissions that a client application can request when obtaining an access token. You can use scopes to fine-tune the level of access granted to the client. For example, an OAuth 2.0 request might include the scope read:profile, indicating that the client application is requesting read-only access to the user’s profile information. Another request might include the scope write:photos, indicating the client’s need to write to the user’s photo collection. In Amazon Cognito, you can define custom scopes along with standard OAuth 2.0 scopes such as openid, profile, email, or phone to align with your application’s requirements. You can use this flexibility to manage access permissions efficiently and securely.
A typical high-level OAuth 2.0 flow looks like the Figure 1:
Figure 1: OAuth 2.0 flow
Below are the steps involved in the OAuth 2.0 flow
The client requests authorization from the resource owner. This is done through the authorization server (Amazon Cognito) as an intermediary.
The resource owner provides the authorization grant to the client. This can be one of the many grant types, which are discussed in detail in the next paragraph. The type of grant used depends on the method used by the client to request authorization from the resource owner.
The client requests an access token by authenticating with Cognito.
Cognito authenticates the client (the authentication method based on the grant type) and issues an access token if the authorization is valid.
The access token is presented to the resource server as the client requests the protected resource.
The resource server checks the access token’s signature and attributes and serves the request if it is valid.
There are several different grant types, four of which are described in the following sections.
Authorization code grant
The authorization code grant type is used by clients to securely exchange an authorization code for an access token. It’s used by both web applications and native applications to get an access token after a user authenticates to an application. After the user returns to the client through the redirect URI (the URL where the authentication server redirects the browser after it authorizes the user), the application gets the authorization code from the URL and uses it to request an access token.
This grant type is suitable for general cases as only one authentication flow is used, regardless of what operation is performed or who is performing it. This grant is considered secure as it requests an access token with a single-use code instead of exposing the actual access tokens. This helps prevent the application from potentially accessing user credentials.
Figure 2: Authorization code grant flow
Below are the steps involved in the authorization code grant flow
The process begins with the client initiating the sequence, directing the user-agent (that is, the browser) of the resource owner to the authorization endpoint. In this action, the client provides its client identifier, the scope it’s requesting, a local state, and a redirection URI to which the authorization server (Amazon Cognito) will return the user agent after either granting or denying access.
Cognito authenticates the resource owner (through the user agent) and establishes whether the resource owner grants or denies the client’s access request using user pool authentication.
Cognito redirects the user agent back to the client using the redirection URI that was provided in step (1) with an authorization code in the query string (such as http://www.example.com/webpage?code=<authcode>).
The client requests an access token from the Cognito’s token endpoint by including the authorization code received in step (3). When making the request, the client authenticates with the Cognito typically with a client ID and a secret. The client includes the redirection URI used to obtain the authorization code for verification.
Cognito authenticates the client, validates the authorization code, and makes sure that the redirection URI received matches the URI used to redirect the client in step (3). If valid, Cognito responds with an access token.
An implementation of the authorization code grant using Amazon Cognito looks like the following:
An application makes an HTTP GET request to _DOMAIN/oauth2/authorize, where AUTH_DOMAIN represents the user pool’s configured domain. This request includes the following query parameters:
response_type – Set to code for this grant type.
client_id – The ID for the desired user pool app client.
redirect_uri – The URL that a user is directed to after successful authentication.
state (optional but recommended) – A random value that’s used to prevent cross-site request forgery (CSRF) attacks.
scope (optional) – A space-separated list of scopes to request for the generated tokens. Note that:
An ID token is only generated if the openid scope is requested.
The phone, email, and profile scopes can only be requested if openid is also requested.
A vended access token can only be used to make user pool API calls if aws.cognito.signin.user.admin (user pool’s reserved API scope) is requested.
identity_provider (optional) – Indicates the provider that the end user should authenticate with.
idp_identifier (optional) – Same as identity_provider but doesn’t expose the provider’s real name.
nonce (optional) – A random value that you can add to the request. The nonce value that you provide is included in the ID token that Amazon Cognito issues. To guard against replay attacks, your app can inspect the nonce claim in the ID token and compare it to the one you generated. For more information about the nonce claim, see ID token validation in the OpenID Connect standard.
A CSRF token is returned in a cookie. If an identity provider was specified in the request from step 1, the rest of this step is skipped. The user is automatically redirected to the appropriate identity provider’s authentication page. Otherwise, the user is redirected to https://AUTH_DOMAIN/login (which hosts the auto-generated UI) with the same query parameters set from step 1. They can then either authenticate with the user pool or select one of the third-party providers that’s configured for the designated app client.
The user authenticates with their identity provider through one of the following means:
If the user uses the native user pool to authenticate, the hosted UI submits the user’s credentials through a POST request to https://AUTH_DOMAIN/login (including the original query parameters) along with some additional metadata.
If the user selects a different identity provider to authenticate with, the user is redirected to that identity provider’s authentication page. After successful authentication the provider redirects the user to https://AUTH_DOMAIN/saml2/idpresponse with either an authorization token in the code query parameter or a SAML assertion in a POST request.
After Amazon Cognito verifies the user pool credentials or provider tokens it receives, the user is redirected to the URL that was specified in the original redirect_uri query parameter. The redirect also sets a code query parameter that specifies the authorization code that was vended to the user by Cognito.
The custom application that’s hosted at the redirect URL can then extract the authorization code from the query parameters and exchange it for user pool tokens. The exchange occurs by submitting a POST request to https://AUTH_DOMAIN/oauth2/token with the following application/x-www-form-urlencoded parameters:
grant_type – Set to authorization_code for this grant.
code – The authorization code that’s vended to the user.
client_id – Same as from the request in step 1.
redirect_uri – Same as from the request in step 1.
If the client application that was configured with a secret, the Authorization header for this request is set as Basic BASE64(CLIENT_ID:CLIENT_SECRET), where BASE64(CLIENT_ID:CLIENT_SECRET) is the base64 representation of the application client ID and application client secret, concatenated with a colon.
The JSON returned in the resulting response has the following keys:
refresh_token – A valid user pool refresh token. This can be used to retrieve new tokens by sending it through a POST request to https://AUTH_DOMAIN/oauth2/token, specifying the refresh_token and client_id parameters, and setting the grant_type parameter to refresh_token.
id_token – A valid user pool ID token. Note that an ID token is only provided if the openid scope was requested.
expires_in – The length of time (in seconds) that the provided ID or access tokens are valid.
token_type – Set to Bearer.
Here are some of the best practices to be followed when using the authorization code grant:
Use the Proof Key for Code Exchange (PKCE) extension with the authorization code grant, especially for public clients such as a single page web application. This is discussed in more detail in the following section.
Regularly rotate client secrets and credentials to minimize the risk of unauthorized access.
Implement session management to handle user sessions securely. This involves managing access token lifetimes, storing tokens, rotating refresh tokens, implementing token revocations and providing easy logout mechanisms that invalidate access and refresh tokens on user’s devices.
Authorization code grant with PKCE
To enhance security when using the authorization code grant, especially in public clients such as native applications, the PKCE extension was introduced. PKCE adds an extra layer of protection by making sure that only the client that initiated the authorization process can exchange the received authorization code for an access token. This combination is sometimes referred to as a PKCE grant.
It introduces a secret called the code verifier, which is a random value created by the client for each authorization request. This value is then hashed using a transformation method such as SHA256—this is now called the code challenge. The same steps are followed as the flow from Figure 2, however the code challenge is now added to the query string for the request to the authorization server (Amazon Cognito). The authorization server stores this code challenge for verification after the authentication process and redirects back with an authorization code. This authorization code along with the code verifier is sent to the authorization server, which then compares the previously stored code challenge with the code verifier. Access tokens are issued after the verification is successfully completed. Figure 3 outlines this process.
Figure 3: Authorization code grant flow with PKCE
Authorization code grant with PKCE implementation is identical to authorization code grant except that Step 1 requires two additional query parameters:
code_challenge – The hashed, base64 URL-encoded representation of a random code that’s generated client side (code verifier). It serves as a PKCE, which mitigates bad actors from being able to use intercepted authorization codes.
code_challenge_method – The hash algorithm that’s used to generate the code_challenge. Amazon Cognito currently only supports setting this parameter to S256. This indicates that the code_challenge parameter was generated using SHA-256.
In step 5, when exchanging the authorization code with the user pool token, include an additional parameter:
code_verifier – The base64 URL-encoded representation of the unhashed, random string that was used to generate the PKCE code_challenge in the original request.
Implicit grant (not recommended)
Implicit grant was an OAuth 2.0 authentication grant type that allowed clients such as single-page applications and mobile apps to obtain user access tokens directly from the authorization endpoint. The grant type was implicit because no intermediate credentials (such as an authorization code) were issued and later used to obtain an access token. The implicit grant has been deprecated and it’s recommended that you use authorization code grant with PKCE instead. An effect of using the implicit grant was that it exposed access tokens directly in the URL fragment, which could potentially be saved in the browser history, intercepted, or exposed to other applications residing on the same device.
Figure 4: Implicit grant flow
The implicit grant flow was designed to enable public client-side applications—such as single-page applications or mobile apps without a backend server component—to exchange authorization codes for tokens.
Steps 1, 2, and 3 of the implicit grant are identical to the authorization code grant steps, except that the response_type query parameter is set to token. Additionally, while a PKCE challenge can technically be passed, it isn’t used because the /oauth2/token endpoint is never accessed. The subsequent steps—starting with step 4—are as follows:
After Amazon Cognito verifies the user pool credentials or provider tokens it receives, the user is redirected to the URL that was specified in the original redirect_uri query parameter. The redirect also sets the following query parameters:
expires_in – The length of time (in seconds) that the provided ID or access tokens are valid for.
token_type – Set to Bearer.
id_token – A valid user pool ID token. Note that an ID token is only provided if the openid scope was requested.
Note that no refresh token is returned during an implicit grant, as specified in the RFC standard.
The custom application that’s hosted at the redirect URL can then extract the access token and ID token (if they’re present) from the query parameters.
Here are some best practices for implicit grant:
Make access token lifetimes short. Implicit grant tokens can’t be revoked, so expiry is the only way to end their validity.
Implicit grant type is deprecated and should be used only for scenarios where a backend server component can’t be implemented, such as browser-based applications.
Client credentials grant
The client credentials grant is for machine-to-machine authentication. For example, a third-party application must verify its identity before it can access your system. The client can request an access token using only its client credentials (or other supported means of authentication) when the client is requesting access to the protected resources under its control or those of another resource owner that have been previously arranged with the authorization server.
The client credentials grant type must be used only by confidential clients. This means the client must have the ability to protect a secret string from users. Note that to use the client credentials grant, the corresponding user pool app client must have an associated app client secret.
Figure 5: Client credentials grant
The flow illustrated in Figure 5 includes the following steps:
The client authenticates with the authorization server using a client ID and secret and requests an access token from the token endpoint.
The authorization server authenticates the client, and if valid, issues an access token.
The detailed steps for the process are as follows:
The application makes a POST request to https://AUTH_DOMAIN/oauth2/token, and specifies the following parameters:
grant_type – Set to client_credentials for this grant type.
client_id – The ID for the desired user pool app client.
scope – A space-separated list of scopes to request for the generated access token. Note that you can only use a custom scope with the client credentials grant.
In order to indicate that the application is authorized to make the request, the Authorization header for this request is set as Basic BASE64(CLIENT_ID:CLIENT_SECRET), where BASE64(CLIENT_ID:CLIENT_SECRET) is the base64 representation of the client ID and client secret, concatenated with a colon.
The Amazon Cognito authorization server returns a JSON object with the following keys:
expires_in – The length of time (in seconds) that the provided access token is valid.
token_type – Set to Bearer.
Note that, for this grant type, an ID token and a refresh token aren’t returned.
The application uses the access token to make requests to an associated resource server.
The resource server validates the received token and, if everything checks out, processes the request from the app.
Following are a few recommended practices while using the client credentials grant:
Store client credentials securely and avoid hardcoding them in your application. Use appropriate credential management practices, such as environment variables or secret management services.
Limit use cases. The client credentials grant is suitable for machine-to-machine authentication in highly trusted scenarios. Limit its use to cases where other grant types are not applicable.
Extension grant
Extension grants are a way to add support for non-standard token issuance scenarios such as token translation, delegation, or custom credentials. It lets you exchange access tokens from a third-party OAuth 2.0 authorization service with access tokens from Amazon Cognito. By defining the grant type using an absolute URI (determined by the authorization server) as the value of the grant_type argument of the token endpoint, and by adding other parameters required, the client can use an extension grant type.
An example of an extension grant is OAuth 2.0 device authorization grant (RFC 8628). This authorization grant makes it possible for internet-connected devices with limited input capabilities or that lack a user-friendly browser (such as wearables, smart assistants, video-streaming devices, smart-home automation, and health or medical devices) to review the authorization request on a secondary device, such as a smartphone, that has more advanced input and browser capabilities.
Some of the best practices to be followed when deciding to use extension grants are:
Extension grants are for non-standard token issuance scenarios. Use them only when necessary, and thoroughly document their use and purpose.
Conduct security audits and code reviews when implementing Extension grants to identify potential vulnerabilities and mitigate risks.
While Amazon Cognito doesn’t natively support extension grants currently, here is an example implementation of OAuth 2.0 device grant flow using AWS Lambda and Amazon DynamoDB.
Conclusion
In this blog post, we’ve reviewed various OAuth 2.0 grants, each catering to specific application needs, The authorization code grant ensures secure access for web applications (and offers additional security with the PKCE extension), and the client credentials grant is ideal for machine-to-machine authentication. Amazon Cognito acts as an encompassing identity platform, streamlining user authentication, authorization, and integration. By using these grants and the features provided by Cognito, developers can enhance security and the user experience in their applications. For more information and examples, see OAuth 2.0 grants in the Cognito Developer Guide.
Now that you understand implementing OAuth 2.0 grants in Amazon Cognito, see How to customize access tokens in Amazon Cognito user pools to learn about customizing access tokens to make fine-grained authorization decisions and provide a differentiated end-user experience.
If you have feedback about this post, submit comments in the Comments section below. If you have questions about this post, contact AWS Support.
The collective thoughts of the interwebz
Manage Consent
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.