<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Principle AI Inc Engineering Blog]]></title><description><![CDATA[Principle AI is a startup focused on helping businesses build and deploy safe AI models.]]></description><link>https://blog.principle-ai.com</link><generator>RSS for Node</generator><lastBuildDate>Tue, 14 Apr 2026 02:19:08 GMT</lastBuildDate><atom:link href="https://blog.principle-ai.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[What is Model Context Protocol (MCP)?]]></title><description><![CDATA[https://www.youtube.com/watch?v=sShDyqX7Y-0
 
If you have more questions about AI and want AI mentorship please reach out to us on principle-ai.com
Model Context Protocol
Anthropic has released this protocol that allows GenAI models to use external t...]]></description><link>https://blog.principle-ai.com/what-is-model-context-protocol-mcp</link><guid isPermaLink="true">https://blog.principle-ai.com/what-is-model-context-protocol-mcp</guid><dc:creator><![CDATA[Tanvi Nadkarni]]></dc:creator><pubDate>Thu, 10 Jul 2025 01:38:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1752111422517/bc12b662-8450-43ce-8f7c-6bf8f5459b57.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=sShDyqX7Y-0">https://www.youtube.com/watch?v=sShDyqX7Y-0</a></div>
<p> </p>
<p>If you have more questions about AI and want AI mentorship please reach out to us on principle-ai.com</p>
<h2 id="heading-model-context-protocol">Model Context Protocol</h2>
<p>Anthropic has released this protocol that allows GenAI models to use external tools and incorporate the response of those tools into their response.</p>
]]></content:encoded></item><item><title><![CDATA[What is agentic AI ?]]></title><description><![CDATA[https://www.youtube.com/watch?v=68ANA-TbRik
 
Introduction
Agentic AI is AI with agency. Which means instead of simply asking a specific problem to be solved, an AI system is given a broad goal and asked to solve it. For example “organize a birthday ...]]></description><link>https://blog.principle-ai.com/what-is-agentic-ai</link><guid isPermaLink="true">https://blog.principle-ai.com/what-is-agentic-ai</guid><category><![CDATA[agentic AI]]></category><dc:creator><![CDATA[Tanvi Nadkarni]]></dc:creator><pubDate>Sat, 25 Jan 2025 20:28:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1737835928467/8098cea9-1772-4aeb-9d81-c242babcdbd4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=68ANA-TbRik">https://www.youtube.com/watch?v=68ANA-TbRik</a></div>
<p> </p>
<h2 id="heading-introduction">Introduction</h2>
<p><a target="_blank" href="https://aiauthority.dev/rise-of-agentic-ai">Agentic AI is AI with agency.</a> Which means instead of simply asking a specific problem to be solved, an AI system is given a broad goal and asked to solve it. For example “organize a birthday party”. The AI is supposed to use its own agency to get things done. As AI becomes better, we have reached a point where agentic AI has become a theoretical possibility and with some constraints a practical reality.</p>
<p>In this post we will give you more detailed overview of what agentic AI is and what to expect in coming few months.</p>
<h2 id="heading-what-makes-an-ai-agentic">What makes an AI agentic ?</h2>
<p>For an AI to be agentic it needs to have following characteristics.</p>
<ul>
<li><p>Autonomy</p>
</li>
<li><p>Goal-oriented</p>
</li>
<li><p>Adaptability</p>
</li>
<li><p>Decision-making</p>
</li>
</ul>
<p>Agentic system should be autonomous in a sense it should without a human constantly making decisions for it. Occasional human permission should be fine but the agent itself should work totally on its own,</p>
<p>Agentic system should always work towards a specific goal and not exist in vacuum. For example, one goal could be to “buy these sneakers when they are the cheapest”.</p>
<p>Adaptability refers to human like ability to react to unexpected changes in environment. It should not just fail but should rather look for alternatives.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1737836883333/9b248450-d80a-4797-837c-4a7a1171aa2c.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-self-driving-cars-is-a-great-example-of-agentic-system">Self driving cars is a great example of agentic system</h2>
<p>Google’s fully self driving Waymo cars are a great example of a complex but very real agentic ai system. They can drive from point A to B very reliably without any input from a human and adapt to changing road conditions.</p>
<h2 id="heading-dangers-of-agentic-ai">Dangers of Agentic AI</h2>
<p>There are dangers associated with autonomous AI systems. As like all AI systems they can make mistakes, not realize it is a mistake and double down on the mistake. For example, an agent asked to book a good flight deal might book it multiple times wasting lot of money. Also, the agent might get tricked by bad actors into giving away credit card numbers. This is why agentic AI needs rigorous testing and good constraints to guard against such failures.</p>
<h2 id="heading-some-upcoming-ai-agents">Some upcoming AI Agents</h2>
<p>Salesforce and others are teaming together to create virtual employees that can take over a lot of work from real humans from sales, customer service to after sales support. A lot of this work is open ended and yet somewhat constrained.</p>
<p>Many banks are looking at replacing their customer support and real bank staff with AI agents. Bloomberg reported that the <a target="_blank" href="https://www.fintech-core.com/generative-ai-is-likely-going-to-cause-job-loss-in-traditional-banking-industry">banking sector might look at 200K jobs replaced by AI agents</a> pretty soon.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1737836893436/7429419b-bfa7-4ab0-9fcd-e7964bfaaa37.png" alt class="image--center mx-auto" /></p>
]]></content:encoded></item><item><title><![CDATA[Design Instagram Feed using Generative AI]]></title><description><![CDATA[At PrincipleAI, we stay one step ahead on all things AI, so you don’t have to worry. We bring you handpicked AI-related news and technical deep dives. Our most popular series is about system design. In this post, we are going to design an Instagram-l...]]></description><link>https://blog.principle-ai.com/design-instagram-feed-using-generative-ai</link><guid isPermaLink="true">https://blog.principle-ai.com/design-instagram-feed-using-generative-ai</guid><category><![CDATA[Artificial Intelligence]]></category><dc:creator><![CDATA[Tanvi Nadkarni]]></dc:creator><pubDate>Fri, 24 Jan 2025 17:42:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1737739848275/fbe5aa44-ce2f-4b22-855a-3ae81d35a4ff.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>At PrincipleAI, we stay one step ahead on all things AI, so you don’t have to worry. We bring you handpicked AI-related news and technical deep dives. Our most popular series is about system design. In this post, we are going to design an <a target="_blank" href="https://aiauthority.fastx.dev/ai-recommendation-system">Instagram-like feed using generative AI</a>.</p>
<h2 id="heading-introduction">Introduction</h2>
<p>The real world AI deployments are complex. We have done a video teaching the basics of such deployment <a target="_blank" href="https://www.youtube.com/watch?v=NUlLDY16QZU">here</a>. But these days interviewers ask questions to get a sense of your knowledge about generative AI.</p>
<p>We need to design an Instagram-like feed using generative AI. In this task, a user should see posts ranked in a way that encourages more engagement. The user follows their friends on the platform, so we need to include all relevant posts from them. We also need to mix in trending posts from across the platform that align with the user's personal interests. We determine these interests based on the user's actions within the app.</p>
<h2 id="heading-solution">Solution</h2>
<p>The solution has two parts. First, we need to store the user's potential posts in the database, which we keep in a vector database. We also store trending posts in the same database. When it's time to generate the feed, we query the vector database to get a list of posts.</p>
<p>The second part of the solution is ranking. This is done by the model. Since we use a large language model, we treat the model's logic as a black box. We can use multi-shot prompting to explain to the LLM the types of posts the user has interacted with and ask the model to rank the given set of posts based on that information.</p>
<h2 id="heading-video">Video</h2>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=NQeJIpBdpQY">https://www.youtube.com/watch?v=NQeJIpBdpQY</a></div>
]]></content:encoded></item><item><title><![CDATA[Preparing for System Design : Starting point]]></title><description><![CDATA[We have prepared an elaborate list of terms you need to learn as you start your system design journey. We are not going to explain these terms to you but simply list them out. We might cover them in detail in future posts. So subscribe to the blog if...]]></description><link>https://blog.principle-ai.com/preparing-for-system-design-starting-point</link><guid isPermaLink="true">https://blog.principle-ai.com/preparing-for-system-design-starting-point</guid><category><![CDATA[System Design]]></category><dc:creator><![CDATA[Tanvi Nadkarni]]></dc:creator><pubDate>Tue, 07 Jan 2025 04:15:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1736223304915/76a1dffe-ae71-4cd8-b3c9-80f3b4d745ad.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>We have prepared an elaborate list of terms you need to learn as you start your system design journey. We are not going to explain these terms to you but simply list them out. We might cover them in detail in future posts. So subscribe to the blog if you want them.</p>
<p>If you do not know what any of these terms mean, it means you are not prepared. So spend time learning it. Use it as a checklist.</p>
<p><strong>1. Fundamental Concepts</strong></p>
<ul>
<li><p><strong>Scalability:</strong> Ability of a system to handle growing amounts of data and traffic.</p>
</li>
<li><p><strong>Reliability:</strong> Ability of a system to consistently perform its intended function without failure.</p>
</li>
<li><p><strong>Availability:</strong> The percentage of time a system is operational and accessible.</p>
</li>
<li><p><strong>Consistency:</strong> Ensuring all users see the same data at the same time.</p>
</li>
<li><p><strong>Efficiency:</strong> Optimal use of resources (CPU, memory, bandwidth) to achieve performance.</p>
</li>
<li><p><strong>Latency:</strong> Time taken for a request to be processed and a response received.</p>
</li>
<li><p><strong>Throughput:</strong> Number of requests a system can handle per unit of time.</p>
</li>
<li><p><strong>CAP Theorem:</strong> States that it's impossible for a distributed system to simultaneously provide Consistency, Availability, and Partition tolerance; you must choose two.</p>
</li>
<li><p><strong>ACID Properties:</strong> (Atomicity, Consistency, Isolation, Durability) A set of properties that guarantee reliable database transactions.</p>
</li>
</ul>
<p><strong>2. Architectural Patterns</strong></p>
<ul>
<li><p><strong>Client-Server:</strong> A model where clients request services from a central server.</p>
</li>
<li><p><strong>Microservices:</strong> Breaking down an application into small, independent services.</p>
</li>
<li><p><strong>Message Queues:</strong> Components that allow asynchronous communication between services.</p>
</li>
<li><p><strong>Load Balancing:</strong> Distributing traffic across multiple servers to prevent overload.</p>
</li>
<li><p><strong>Caching:</strong> Storing frequently accessed data in a fast-access location.</p>
</li>
<li><p><strong>Databases (SQL, NoSQL):</strong> Organized collections of data for storage and retrieval.</p>
<ul>
<li><p><strong>Relational Databases (SQL):</strong> Structured data organized in tables with relationships.</p>
</li>
<li><p><strong>NoSQL Databases:</strong> Flexible schema for unstructured or semi-structured data.</p>
</li>
</ul>
</li>
<li><p><strong>CDN (Content Delivery Network):</strong> A geographically distributed network of servers that store copies of website assets to deliver content faster to users.</p>
</li>
<li><p><strong>Saga Pattern :</strong> A distributed asynchronous processing pattern.</p>
</li>
</ul>
<p><strong>3. Specific Technologies &amp; Concepts</strong></p>
<ul>
<li><p><strong>REST APIs:</strong> A standard for building web services that use HTTP methods (GET, POST, PUT, DELETE).</p>
</li>
<li><p><strong>HTTP:</strong> (Hypertext Transfer Protocol) The foundation of data communication on the web.</p>
</li>
<li><p><strong>DNS (Domain Name System):</strong> Translates domain names into IP addresses.</p>
</li>
<li><p><strong>TCP/IP:</strong> The suite of protocols that govern the internet.</p>
</li>
<li><p><strong>WebSockets:</strong> Enables real-time, two-way communication between client and server.</p>
</li>
<li><p><strong>Sharding:</strong> Horizontal partitioning of a database to distribute data across multiple machines.</p>
</li>
</ul>
<p><strong>4. Design Considerations</strong></p>
<ul>
<li><p><strong>Vertical Scaling:</strong> Increasing the resources of a single server (CPU, RAM).</p>
</li>
<li><p><strong>Horizontal Scaling:</strong> Adding more servers to a system to handle increased load.</p>
</li>
<li><p><strong>Database Indexing:</strong> Creating data structures to speed up data retrieval.</p>
</li>
<li><p><strong>Data Replication:</strong> Creating copies of data to improve availability and fault tolerance.</p>
</li>
<li><p><strong>Rate Limiting:</strong> Controlling the rate of traffic to a system to prevent abuse and overload.</p>
</li>
<li><p><strong>Circuit Breaker:</strong> A pattern to prevent cascading failures in a distributed system.</p>
</li>
</ul>
<h2 id="heading-databases">Databases</h2>
<ul>
<li><p><strong>MySQL:</strong> Open-source, widely used, good for general purpose web applications.</p>
</li>
<li><p><strong>PostgreSQL:</strong> Advanced features, strong SQL compliance, good for complex data models.</p>
</li>
<li><p><strong>Oracle:</strong> Enterprise-grade, highly scalable, expensive but robust.</p>
</li>
<li><p><strong>MS SQL Server:</strong> Microsoft ecosystem, good integration with .NET, strong for transactional workloads.</p>
</li>
<li><p><strong>MongoDB:</strong> Flexible schema, good for document-oriented data, popular for web and mobile apps.</p>
</li>
<li><p><strong>Cassandra:</strong> Highly available, fault-tolerant, good for distributed systems and high write throughput.</p>
</li>
<li><p><strong>Redis:</strong> In-memory, very fast, excellent for caching and real-time data.</p>
</li>
<li><p><strong>Amazon DynamoDB:</strong> Fully managed, scalable, pay-as-you-go, integrated with the AWS ecosystem.</p>
</li>
<li><p><strong>Neo4j:</strong> Handles relationships efficiently, good for social networks, recommendation engines.</p>
</li>
<li><p><strong>Elasticsearch:</strong> Powerful search and analytics, good for log analysis, full-text search.</p>
</li>
<li><p><strong>ClickHouse:</strong> High-performance analytics, good for large datasets and complex queries.</p>
</li>
</ul>
<h2 id="heading-caches">Caches</h2>
<p><strong>1. CPU Cache:</strong> Small, very fast memory within the CPU that stores frequently used instructions and data. (e.g., L1, L2, L3 caches)</p>
<p><strong>2. Disk Cache:</strong> Portion of RAM used to store frequently accessed data from the hard drive.</p>
<p><strong>3. Web Cache (Browser Cache):</strong> Stores website assets (images, scripts, etc.) locally on the user's browser to speed up page loading.</p>
<p><strong>4. Server-Side Cache:</strong> Caches data on the server to reduce database load and improve response times. <strong><em>Object Cache:</em></strong> <em>Stores specific data objects like database query results.</em> <strong>Page Cache:</strong> Caches entire web pages or fragments of pages. * <strong>Opcode Cache:</strong> Stores precompiled code to avoid redundant compilation.</p>
<p><strong>5. CDN Cache:</strong> Stores copies of website content on servers geographically closer to users for faster delivery.</p>
<p><strong>6. DNS Cache:</strong> Stores DNS records locally to speed up website lookups.</p>
<p><strong>7. Distributed Cache:</strong> A cache that is spread across multiple servers, often used in large-scale systems. (e.g., Redis, Memcached)</p>
<h2 id="heading-microservices">Microservices</h2>
<p><strong>1. Microservice:</strong> A small, independent, and loosely coupled service that performs a specific business function.</p>
<p><strong>2. API Gateway:</strong> A single entry point for all clients, handling routing, authentication, and rate limiting for microservices.</p>
<p><strong>3. Service Discovery:</strong> A mechanism for microservices to locate and communicate with each other dynamically.</p>
<p><strong>4. Service Mesh:</strong> A dedicated infrastructure layer for managing communication between microservices, providing features like load balancing, service discovery, and security.</p>
<p><strong>5. Containerization:</strong> Packaging a microservice and its dependencies into a container (e.g., Docker) for easy deployment and portability.</p>
<p><strong>6. Orchestration:</strong> Automating the deployment, scaling, and management of microservices, often using tools like Kubernetes.</p>
<p><strong>7. Circuit Breaker:</strong> A pattern to prevent cascading failures by stopping requests to a failing service.</p>
<p><strong>8. Distributed Tracing:</strong> Tracking requests across multiple microservices to monitor performance and identify bottlenecks.</p>
<p><strong>9. Event-Driven Architecture:</strong> Microservices communicate through events, enabling asynchronous and decoupled interactions.</p>
<p><strong>10. CQRS (Command Query Responsibility Segregation):</strong> Separating read and write operations to improve performance and scalability.</p>
<h2 id="heading-message-queues">Message Queues</h2>
<ul>
<li><p><strong>Message Queue:</strong> A temporary storage buffer for messages waiting to be processed.</p>
</li>
<li><p><strong>Producer:</strong> An application that creates and sends messages to a queue.</p>
</li>
<li><p><strong>Consumer:</strong> An application that receives and processes messages from a queue.</p>
</li>
<li><p><strong>Queue Depth:</strong> The number of messages currently held in a queue.</p>
</li>
<li><p><strong>Message Broker:</strong> A middleware component that manages the flow of messages between producers and consumers. (e.g., RabbitMQ, Kafka)</p>
</li>
<li><p><strong>Acknowledgement (ACK):</strong> A signal from a consumer to the queue that a message has been successfully processed.</p>
</li>
<li><p><strong>Dead-letter Queue:</strong> A queue that stores messages that failed to be processed.</p>
</li>
<li><p><strong>Message Priority:</strong> Assigning different levels of importance to messages for processing order.</p>
</li>
<li><p><strong>Message Durability:</strong> Ensuring messages are not lost even if the message broker fails.</p>
</li>
<li><p><strong>Message Ordering:</strong> Guaranteeing messages are processed in the order they were sent.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Master Protocol Buffers for System Design]]></title><description><![CDATA[In system design interviews high level design is relatively simpler if you know the basic building blocks. For low level design you are expected to design the API interfaces. How would you do that ? A lot of people either like to talk in terms of RES...]]></description><link>https://blog.principle-ai.com/master-protocol-buffers-for-system-design</link><guid isPermaLink="true">https://blog.principle-ai.com/master-protocol-buffers-for-system-design</guid><category><![CDATA[protocol-buffers]]></category><category><![CDATA[System Design]]></category><dc:creator><![CDATA[Tanvi Nadkarni]]></dc:creator><pubDate>Thu, 02 Jan 2025 00:36:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1735775282629/d460ea40-e478-452f-88df-5dbee962a355.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In system design interviews high level design is relatively simpler if you know the basic building blocks. For low level design you are expected to design the API interfaces. How would you do that ? A lot of people either like to talk in terms of REST apis or a programming language specific APIs.</p>
<p>However, I recommend candidates to master protocol buffers as a way to describe your API interfaces. Even if you plan to use REST and not GRPC, it is trivial create an adapter around GRPC to support REST interfaces. But why is ProtoBuff so important ?</p>
<h2 id="heading-protocol-buffers-are-typed-json-is-not">Protocol Buffers are typed JSON is not.</h2>
<p>If you are using JSON to describe your API input output, you will encounter the problem of describing types to the interviewer.</p>
<p>For example consider a photo object.</p>
<pre><code class="lang-json"><span class="hljs-comment">// Photo Object</span>
{
  fileName: <span class="hljs-string">""</span>,
  contentType: <span class="hljs-string">""</span>, 
  base64EncodedImage:<span class="hljs-string">""</span>
  author: { .... }
}

<span class="hljs-comment">// Video object </span>
{
  fileName: <span class="hljs-string">""</span>,
  contentType: <span class="hljs-string">""</span>, 
  base64EncodedVideo:<span class="hljs-string">""</span>
  author: { .... }
}
</code></pre>
<p>The problem here is that how do you communicate types of different fields ? What exactly is an authors object ? Also how do you represent the fact that Author object is similar for both Video and Photo ?</p>
<p>Compared to this check this</p>
<pre><code class="lang-plaintext">message Photo {
  string fileName = 1; 
  enum ContentType contentType = 2; 
  bytes imageData = 3; 
  Author author = 4;
}

message Video {
  string fileName = 1; 
  enum ContentType contentType = 2; 
  bytes videoData = 3; 
  Author author = 4;
}

message Author {
 long userId = 1; 
 repeated Role roles = 2; 
}

enum ContentType {
  BINARY_PNG = 1; 
  BINARY_MP4 = 2; 
}
</code></pre>
<p>Not only this is extremely concise, it also answers a lot of questions about the types and reusability of objects. It is also better to store protobuff in storage because they optimize a lot of storage related aspects.</p>
<p>If you propose to use Cloud Spanner database in GCP, then you can actually describe your database schema using protocol buffers as well.</p>
<p>Similarly, if you want to describe API interfaces it is much better to describe them as gRPC interfaces using protocol buffers instead of REST.</p>
<pre><code class="lang-plaintext">Protocol Buffers

syntax = "proto3";

service MultiMediaService {
  rpc UploadPhoto (stream UploadPhotoRequest) returns (UploadPhotoResponse) {}
  rpc UploadVideo (stream UploadVideoRequest) returns (UploadVideoResponse) {}
}

message UploadPhotoRequest {
  bytes chunk_data = 1; // Chunk of the photo data
  string file_name = 2; // Name of the photo file
  string content_type = 3; // MIME type of the photo (e.g., "image/jpeg")
}

message UploadPhotoResponse {
  string photo_id = 1; // Unique ID for the uploaded photo
  string photo_url = 2; // URL to access the photo
}

message UploadVideoRequest {
  bytes chunk_data = 1; // Chunk of the video data
  string file_name = 2; // Name of the video file
  string content_type = 3; // MIME type of the video (e.g., "video/mp4")
}

message UploadVideoResponse {
  string video_id = 1; // Unique ID for the uploaded video
  string video_url = 2; // URL to access the video
}
</code></pre>
<p>This avoids the problem of describing HTTP endpoints, proper HTTP methods and JSON input output. Not only this is a better design but also it makes the system design interview more efficient by saving on time.</p>
<h2 id="heading-pitfalls">Pitfalls</h2>
<p>However, it is always a better idea to ask your interviewer if they have any preference between JSON and ProtoBuffs. If the interviewer is not familiar with Protocol Buffers it might only confuse them. In that case stick to JSON.</p>
]]></content:encoded></item><item><title><![CDATA[Design a centralized authentication system]]></title><description><![CDATA[https://www.youtube.com/watch?v=Dh11cxb7WYs
 
Problem statement:
Design a centralized authentication system for millions of users. The objective is to only design authentication system and not authorization system. More than 1M daily active users and...]]></description><link>https://blog.principle-ai.com/design-a-centralized-authentication-system</link><guid isPermaLink="true">https://blog.principle-ai.com/design-a-centralized-authentication-system</guid><dc:creator><![CDATA[Tanvi Nadkarni]]></dc:creator><pubDate>Mon, 30 Dec 2024 07:10:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1735542629741/c3e75db5-b9bf-4aad-83e8-962118eb5643.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=Dh11cxb7WYs">https://www.youtube.com/watch?v=Dh11cxb7WYs</a></div>
<p> </p>
<h2 id="heading-problem-statement">Problem statement:</h2>
<p>Design a centralized authentication system for millions of users. The objective is to only design authentication system and not authorization system. More than 1M daily active users and 100M calls to verify authentication token.</p>
<h2 id="heading-solution-summary">Solution Summary:</h2>
<p>We use a simple JWT based authentication. An AuthenticationService handles most complex operations. We help scaling by using an in memory hot cache that keeps all the active JWTs. A CryptoService is used to sign and verify tokens by cache reduces calls to this service.</p>
]]></content:encoded></item><item><title><![CDATA[Adding LLM to Spring Boot : Start using AI today]]></title><description><![CDATA[Web developers are curious about how to integrate the power of Large Language Models (LLMs) into their projects. It's becoming increasingly clear that LLMs will play an important role in shaping user experiences across all kinds of apps. However, a l...]]></description><link>https://blog.principle-ai.com/adding-llm-to-spring-boot-start-using-ai-today</link><guid isPermaLink="true">https://blog.principle-ai.com/adding-llm-to-spring-boot-start-using-ai-today</guid><dc:creator><![CDATA[Tanvi Nadkarni]]></dc:creator><pubDate>Mon, 30 Dec 2024 02:34:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1735493359906/e6d2e8e7-55d5-4bdf-8e1e-95637bb8ce97.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Web developers are curious about how to integrate the power of Large Language Models (LLMs) into their projects. It's becoming increasingly clear that LLMs will play an important role in shaping user experiences across all kinds of apps. However, a lot of engineers also do not where to start and how to start experimenting.</p>
<p>In this article we will provide you simple steps and code to start using open source LLMs with your app. Before you understand how to use LLMs in your app, please watch our <a target="_blank" href="https://www.youtube.com/watch?v=NUlLDY16QZU&amp;t=1s">high level design video that describe how AI can be used in your app</a>.</p>
<h2 id="heading-ollama">Ollama</h2>
<p>Ollama is an open source tool that makes it simple for you to run any open source model on your server. Open source models such as Meta’s LLama, Google’s Gemma etc. are essentially very large files that you load in memory and using their own APIs you ask them questions. Each open source model has a different interface, different capabilities.</p>
<p>As an application developer it is best not to concern yourself with low level details of the model apis. However, you might want to experiment with different models to figure out which one is better for your needs. Y</p>
<p>Ollama is a wrapper around these open source models and lets you pick and chose the model and create a uniform interface around it.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Model</td><td>Parameters</td><td>Size</td><td>Download</td></tr>
</thead>
<tbody>
<tr>
<td>Llama 3.3</td><td>70B</td><td>43GB</td><td><code>ollama run llama3.3</code></td></tr>
<tr>
<td>Llama 3.2</td><td>3B</td><td>2.0GB</td><td><code>ollama run llama3.2</code></td></tr>
<tr>
<td>Llama 3.2</td><td>1B</td><td>1.3GB</td><td><code>ollama run llama3.2:1b</code></td></tr>
<tr>
<td>Llama 3.2 Vision</td><td>11B</td><td>7.9GB</td><td><code>ollama run llama3.2-vision</code></td></tr>
<tr>
<td>Llama 3.2 Vision</td><td>90B</td><td>55GB</td><td><code>ollama run llama3.2-vision:90b</code></td></tr>
<tr>
<td>Llama 3.1</td><td>8B</td><td>4.7GB</td><td><code>ollama run llama3.1</code></td></tr>
<tr>
<td>Llama 3.1</td><td>405B</td><td>231GB</td><td><code>ollama run llama3.1:405b</code></td></tr>
<tr>
<td>Phi 3 Mini</td><td>3.8B</td><td>2.3GB</td><td><code>ollama run phi3</code></td></tr>
<tr>
<td>Phi 3 Medium</td><td>14B</td><td>7.9GB</td><td><code>ollama run phi3:medium</code></td></tr>
<tr>
<td>Gemma 2</td><td>2B</td><td>1.6GB</td><td><code>ollama run gemma2:2b</code></td></tr>
<tr>
<td>Gemma 2</td><td>9B</td><td>5.5GB</td><td><code>ollama run gemma2</code></td></tr>
<tr>
<td>Gemma 2</td><td>27B</td><td>16GB</td><td><code>ollama run gemma2:27b</code></td></tr>
<tr>
<td>Mistral</td><td>7B</td><td>4.1GB</td><td><code>ollama run mistral</code></td></tr>
<tr>
<td>Moondream 2</td><td>1.4B</td><td>829MB</td><td><code>ollama run moondream</code></td></tr>
<tr>
<td>Neural Chat</td><td>7B</td><td>4.1GB</td><td><code>ollama run neural-chat</code></td></tr>
<tr>
<td>Starling</td><td>7B</td><td>4.1GB</td><td><code>ollama run starling-lm</code></td></tr>
<tr>
<td>Code Llama</td><td>7B</td><td>3.8GB</td><td><code>ollama run codellama</code></td></tr>
<tr>
<td>Llama 2 Uncensored</td><td>7B</td><td>3.8GB</td><td><code>ollama run llama2-uncensored</code></td></tr>
<tr>
<td>LLaVA</td><td>7B</td><td>4.5GB</td><td><code>ollama run llava</code></td></tr>
<tr>
<td>Solar</td><td>10.7B</td><td>6.1GB</td><td><code>ollama run solar</code></td></tr>
</tbody>
</table>
</div><p>This gives you an idea of how useful Ollama is.</p>
<h2 id="heading-using-ollama-with-spring-boot">Using Ollama with Spring Boot</h2>
<p>Ollama is a library that you can install as a command line tool. Once done, you can use that interface to start a server that gives you a REST based interface.</p>
<p>Install ollama</p>
<pre><code class="lang-plaintext">curl -fsSL https://ollama.com/install.sh | sh
</code></pre>
<p>Start the ollama server</p>
<pre><code class="lang-plaintext">./ollama serve

# In a seprate shell

./ollama run llama3.2
</code></pre>
<p>You can then query this server.</p>
<pre><code class="lang-plaintext">curl http://localhost:11434/api/generate -d '{
  "model": "llama3.2",
  "prompt":"Why is the sky blue?"
}'
</code></pre>
<h2 id="heading-integrating-with-spring-boot">Integrating with Spring Boot</h2>
<p>To use ollama with spring boot you should create a separate server that just runs Ollama and use REST interface to make your Spring Boot talk to the server.</p>
<p>Spring Boot has a helpful library that allows you to interface with Ollama server. Just add the following line to your gradle.build file.</p>
<pre><code class="lang-plaintext">dependencies {
    implementation 'org.springframework.ai:spring-ai-ollama-spring-boot-starter'
}
</code></pre>
<p>Once you add this dependency you can configure the ollama parameters right into your spring boot application.</p>
<p>Configuring Ollama parameters.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Property</td><td>Description</td><td>Default</td></tr>
</thead>
<tbody>
<tr>
<td>spring.ai.ollama.base-url</td><td>Base URL where Ollama API server is running.</td><td><a target="_blank" href="http://localhost:11434/"><code>localhost:11434</code></a></td></tr>
</tbody>
</table>
</div><p>Then you can define your custom controller where you can call the Ollama Chat api.</p>
<pre><code class="lang-java"><span class="hljs-meta">@RestController</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ChatController</span> </span>{

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> OllamaChatModel chatModel;

    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ChatController</span><span class="hljs-params">(OllamaChatModel chatModel)</span> </span>{
        <span class="hljs-keyword">this</span>.chatModel = chatModel;
    }

    <span class="hljs-meta">@GetMapping("/ai/generate")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Map&lt;String,String&gt; <span class="hljs-title">generate</span><span class="hljs-params">(<span class="hljs-meta">@RequestParam(value = "message", defaultValue = "Tell me a joke")</span> String message)</span> </span>{
        <span class="hljs-keyword">return</span> Map.of(<span class="hljs-string">"generation"</span>, <span class="hljs-keyword">this</span>.chatModel.call(message));
    }

    <span class="hljs-meta">@GetMapping("/ai/generateStream")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Flux&lt;ChatResponse&gt; <span class="hljs-title">generateStream</span><span class="hljs-params">(<span class="hljs-meta">@RequestParam(value = "message", defaultValue = "Tell me a joke")</span> String message)</span> </span>{
        Prompt prompt = <span class="hljs-keyword">new</span> Prompt(<span class="hljs-keyword">new</span> UserMessage(message));
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.chatModel.stream(prompt);
    }

}
</code></pre>
<p>OllamaChatModel is a standard API to chat with the model. UserMessage implies the prompt that comes from User. We will cover the actual usage of these APIs in future posts. But this gives you a good starting point.</p>
<h2 id="heading-function-calling-with-ollama">Function calling with Ollama</h2>
<p>Ollama is smart enough to actually call methods based on output of the LLM. For example you might want to ask LLM current temperature in a city and then present it to the user. For this LLM might have to call a method inside your app. One way to do this is by creating a function and letting LLM know that it is available. When it needs to be called is smartly determined by LLM.</p>
<pre><code class="lang-java"><span class="hljs-meta">@SpringBootApplication</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OllamaApplication</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        SpringApplication.run(OllamaApplication.class, args);
    }

    <span class="hljs-meta">@Bean</span>
    <span class="hljs-function">CommandLineRunner <span class="hljs-title">runner</span><span class="hljs-params">(ChatClient.Builder chatClientBuilder)</span> </span>{
        <span class="hljs-keyword">return</span> args -&gt; {
            <span class="hljs-keyword">var</span> chatClient = chatClientBuilder.build();

            <span class="hljs-keyword">var</span> response = chatClient.prompt()
                .user(<span class="hljs-string">"What is the weather in Amsterdam and Paris?"</span>)
                .functions(<span class="hljs-string">"weatherFunction"</span>) <span class="hljs-comment">// reference by bean name.</span>
                .call()
                .content();

            System.out.println(response);
        };
    }

    <span class="hljs-meta">@Bean</span>
    <span class="hljs-meta">@Description("Get the weather in location")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Function&lt;WeatherRequest, WeatherResponse&gt; <span class="hljs-title">weatherFunction</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> MockWeatherService();
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MockWeatherService</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Function</span>&lt;<span class="hljs-title">WeatherRequest</span>, <span class="hljs-title">WeatherResponse</span>&gt; </span>{

        <span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">WeatherRequest</span><span class="hljs-params">(String location, String unit)</span> </span>{}
        <span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">WeatherResponse</span><span class="hljs-params">(<span class="hljs-keyword">double</span> temp, String unit)</span> </span>{}

        <span class="hljs-meta">@Override</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> WeatherResponse <span class="hljs-title">apply</span><span class="hljs-params">(WeatherRequest request)</span> </span>{
            <span class="hljs-keyword">double</span> temperature = request.location().contains(<span class="hljs-string">"Amsterdam"</span>) ? <span class="hljs-number">20</span> : <span class="hljs-number">25</span>;
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> WeatherResponse(temperature, request.unit);
        }
    }
}
</code></pre>
<p>Source : <a target="_blank" href="https://spring.io/blog/2024/07/26/spring-ai-with-ollama-tool-support">https://spring.io/blog/2024/07/26/spring-ai-with-ollama-tool-support</a></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Spring boot and Ollama play well together and make it extremely simple to use AI in your apps.</p>
]]></content:encoded></item><item><title><![CDATA[Integrating Gen-AI into your applications - Part 1 - The foundations]]></title><description><![CDATA[Integrating generative AI into your existing applications is one of the major challenges of all businesses. Generative AI has a lot of capabilities and it has simplified how we can use machine learning solutions in usual business workflows. In past t...]]></description><link>https://blog.principle-ai.com/integrating-gen-ai-into-your-applications-part-1-the-foundations</link><guid isPermaLink="true">https://blog.principle-ai.com/integrating-gen-ai-into-your-applications-part-1-the-foundations</guid><category><![CDATA[generative ai]]></category><dc:creator><![CDATA[Tanvi Nadkarni]]></dc:creator><pubDate>Sat, 21 Dec 2024 10:02:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1734772547284/dc6ca83e-3816-4c27-96a0-f46f06edf03b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a target="_blank" href="https://aiauthority.dev/system-design-how-to-start-adding-generative-ai-to-your-product">Integrating generative AI into your existing applications</a> is one of the major challenges of all businesses. Generative AI has a lot of capabilities and it has simplified how we can use machine learning solutions in usual business workflows. In past this was extremely complex as it involved training different models on different data to solve specific problems. In this article series we are going to explore this problem in more detail with several concrete use cases.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">If you find this series useful. You can subscribe to our newsletter and youtube channel to show your appreciation</div>
</div>

<h2 id="heading-the-foundations">The foundations</h2>
<p>Generative AI could mean many things. Large Language Models or LLMs is the most basic type of generative ai technology but we might also have something like Imagen or Midjourney or Sora or Veo. But very likely we are going to use a LLM for a lot of generative ai tasks and hence we will focus on LLM usecases first.</p>
<p>Once you have decided that you need to use GenAI in your application the next job is for the product team to figure out which are some of the areas where Gen AI can help your product get better and more useful. We will create a more structured framework for this later, but first we need to create an engineering foundation that different product teams can rely on to meet their needs.</p>
<h2 id="heading-llm-service">LLM service</h2>
<p>Our advice to organizations is to have single entry point into all your Gen Ai related work. This means a single team is responsible for maintaining the Gen AI inference infra in the organization and owns a generic set of inference APIs other teams could use.</p>
<p>This is sensible because LLMs themselves have extremely simple interface. They take free from text as input and produce text as output. There is really not much to it ultimately.</p>
<p>An LLM service is responsible for running inference for everyone against the models hosted by this service. Such a microservice is maintained by a single team and provides service to multiple other teams in the organization.</p>
<p>Experimentation, analytics and AI safety can thus be implemented at this entry point more uniformly. Also given that inference is expensive we might also want to assign quotas accordingly to each consumer depending on the business need.</p>
<p>Even if you are using third party APIs are like Google’s Gemini, you still need to control access to such a system and standardize how other teams use these GenAI technologies. So it makes sense to create an LLM wrapper around it.</p>
<h2 id="heading-session-storage">Session storage</h2>
<p>LLMs are all about context and hence we might also want to store some contextual data about an LLM prompt. This can be done using a concept called session. This is especially useful if you are going for a conversational AI and LLM needs to access the previous state of the prompt output. Hence we need a good way for the consumers to inform the LLM about the context of the query.</p>
<p>This can be modeled how we model a session in typical web applications. Each consumer “creates” and “ends” a session and the backend service is able to chain all the events that happen with that session Id.</p>
<h2 id="heading-analytics-and-logging">Analytics and logging</h2>
<p>Since Gen-AI technologies are experimental, we need a lot of real time data about how our Gen AI solutions are doing in wild. We can achieve this by logging all Gen AI interactions to a central place where they can be analyzed at a very high level of granularity by our researchers. This data can also be used to fine tune the future models.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>We have put together a video with more details of this sort of LLM Service.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=NUlLDY16QZU">https://www.youtube.com/watch?v=NUlLDY16QZU</a></div>
<p> </p>
<p><strong>Next Part: Data collection, fine tuning and experimentation.</strong></p>
]]></content:encoded></item><item><title><![CDATA[Url shortening service on budget]]></title><description><![CDATA[There are lot of different system design answers for a url shortening service at scale. However, if you are on budget and you want to create something that is simple, cheap and low maintenance here is an interesting one.
We use a simple API gateway f...]]></description><link>https://blog.principle-ai.com/url-shortening-service-on-budget</link><guid isPermaLink="true">https://blog.principle-ai.com/url-shortening-service-on-budget</guid><category><![CDATA[System Design]]></category><dc:creator><![CDATA[Tanvi Nadkarni]]></dc:creator><pubDate>Wed, 18 Dec 2024 04:16:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1734495355345/05afea6f-5f0e-4b13-b448-e324945cd31c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>There are lot of different system design answers for a url shortening service at scale. However, if you are on budget and you want to create something that is simple, cheap and low maintenance here is an interesting one.</p>
<p>We use a simple API gateway for creating the a short url. A url is hashed to a url safe short string and an Amazon AWS S3 object is created. As you know, S3 allows you to set metadata for every S3 object including a 302 url to which the request must be redirected if it is a public object.</p>
<p>S3 objects can be fronted using CloudFront CDN which makes everything global.</p>
<p>We create a bucket “mydomain-urls” and for every new url we create an empy object in the bucket.</p>
<p>mydomain-urls/&lt;hash&gt; and set its metadata to 302 redirect url.</p>
<p>CloudFront can then be setup for this bucket.</p>
<p>We also need to setup a 404 url for the bucket.</p>
<p><img src="https://documents.lucid.app/documents/86df232e-d632-40f7-87df-d8d8ead8e60f/pages/0_0?a=5709&amp;x=-2453&amp;y=719&amp;w=1581&amp;h=880&amp;store=1&amp;accept=image%2F*&amp;auth=LCA%20a201f5b1d3e64b8cee58439cd999b53199017b0d7262de9ce4bfdf483d840198-ts%3D1734491178" alt /></p>
<p><strong>Advantages</strong></p>
<ol>
<li><p>No database required.</p>
</li>
<li><p>No hot cache/redis or multi region deployments needed. (This is offloaded to cloudfront)</p>
</li>
<li><p>One single server is sufficient for a reasonable load.</p>
</li>
<li><p>The “Read” flow is pretty much handled by CloudFront for us which has very good SLA</p>
</li>
<li><p>CloudFront provides both rate limiting and DDoS protection.</p>
</li>
</ol>
<p><strong>Disadvantages</strong></p>
<ol>
<li>No real time stats about requests available but can be done using logs processing.</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Saga Pattern - Architecture guide]]></title><description><![CDATA[Microservices driven architecture is getting increasingly common. Microservices are small independent services that do one thing and one thing right with very clear API boundaries. A complex system is built by using multiple microservices calling eac...]]></description><link>https://blog.principle-ai.com/saga-pattern-architecture-guide</link><guid isPermaLink="true">https://blog.principle-ai.com/saga-pattern-architecture-guide</guid><category><![CDATA[saga]]></category><category><![CDATA[System Architecture]]></category><dc:creator><![CDATA[Tanvi Nadkarni]]></dc:creator><pubDate>Tue, 17 Dec 2024 08:00:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1734377082073/39e86f5c-c7fc-45d1-a896-d471a8446370.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Microservices driven architecture is getting increasingly common. Microservices are small independent services that do one thing and one thing right with very clear API boundaries. A complex system is built by using multiple microservices calling each other. I think of this as lego bricks being used to build a more complex object.</p>
<p>This approach allows for better people management. Small teams can work on their independent code base without worrying too much about other teams. This reduces need to synchronize with other teams and communication overhead.</p>
<p>The disadvantages of microservices is that it might leads to inefficient allocation of compute power, increase RPC communication overhead and debugging might become harder as bug in one system might propagate to other callers.</p>
<h2 id="heading-saga-pattern">Saga Pattern</h2>
<p>In this post we are going to discuss the architectural pattern called “Saga”. Saga in english means a long story of heroic achievement. Modern businesses using technology are often like this. Long chain of multiple events leading to different things. For example user searching for flight tickets and then choosing one, booking one, doing payment, later cancelling the flight etc.</p>
<p>Saga pattern inherently is designed for such complex scenarios to break them down into smaller pieces and help design small self contained microservices.</p>
<p><img src="https://documents.lucid.app/documents/86df232e-d632-40f7-87df-d8d8ead8e60f/pages/0_0?a=4387&amp;x=-2255&amp;y=-1213&amp;w=1190&amp;h=706&amp;store=1&amp;accept=image%2F*&amp;auth=LCA%207ec6b26a189fc94e22e8a884b4cde062f2af239306759f4366b3308a9069cf90-ts%3D1734375546" alt /></p>
<p>In user’s perspective this is a single journey they are taking. In system’s perspective this is one of the possible paths.</p>
<p>A typical travel website supports millions of searches per day but only thousands of tickets get booked each day. Out of those thousands few hundred will eventually get cancelled. So the scalability needs for each of these steps are very different.</p>
<p>Similarly, there are different reasons to send out mails to the customer. Booking emails, payment emails, changes to flight itinerary emails etc.</p>
<p>To make sense of these steps there are two subtypes.</p>
<h2 id="heading-choreographed-saga">Choreographed Saga</h2>
<p>This phrase comes from the world of dance. A dance is a series of steps that each participants take. Every dancer does their own moves and trusts the partner to do their moves. There is no centralized co-ordinator forcing them to make specific moves. It is all determined by convention.</p>
<p>In microservices Choreographed Saga is designed as each micro-service doing its work and reporting its results in a particular communication channel. If the micro-service fails to do its job it reports the failure as well. Any other micro-service that depends on this has to be responsible for taking steps depending on the success or failure result.</p>
<p>For example Booking system might record user’s desire to book a ticket. Hold the ticket and ask user to complete the payment. The payment system reports success or failure result on the channel that booking system is responsible for listening and take next steps accordingly. The failure path handling is often called “compensatory actions”.</p>
<p><img src="https://documents.lucid.app/documents/86df232e-d632-40f7-87df-d8d8ead8e60f/pages/0_0?a=4483&amp;x=-2206&amp;y=-1417&amp;w=2313&amp;h=794&amp;store=1&amp;accept=image%2F*&amp;auth=LCA%207681d6d8cc783c3765d73e92e13b74dbbc2e6778b73c8756606c5409435c9bec-ts%3D1734375546" alt /></p>
<p>Here Booking system asks payment system to process a payment and respond on the reply channel. If the payment system fails to process the payment the booking system will remove the ticket hold. If the payment succeeds then booking system will mark the ticket as sold.</p>
<p>What if the payment succeeds but Booking system fails to mark the ticket as bought ? The booking system is then responsible for issuing a refund request to the payment system.</p>
<p>How the payment system handles payment or refunds, what emails it might send to the user etc. is not determined by Booking system. It only sees the payment system as two micro-service calls. “ProcessPayment” and “RefundPayment”.</p>
<p>Similarly, Payment system does not care at all about why the payment is being made. It only does two things it is being asked to do.</p>
<p>This reduces complexity and makes thing much simpler to engineer.</p>
<p><strong>Pros:</strong></p>
<ol>
<li><p>Good scalability as there are no centralized systems.</p>
</li>
<li><p>Development and testing can be independently done.</p>
</li>
</ol>
<p><strong>Cons:</strong></p>
<ol>
<li><p>Changes to communication protocol is harder.</p>
</li>
<li><p>Bugs can have a domino effect.</p>
</li>
<li><p>Communication design is complex.</p>
</li>
</ol>
<h2 id="heading-conductor-saga">Conductor Saga</h2>
<p>This phrase comes from the world of music where a conductor instructs everyone on what to do. This conductor is a centralized broker who knows all the steps and their logic and is responsible for actions. This makes it easier for engineers to code the logic of flows in a single system.</p>
<p><img src="https://documents.lucid.app/documents/86df232e-d632-40f7-87df-d8d8ead8e60f/pages/0_0?a=4548&amp;x=-2017&amp;y=-783&amp;w=794&amp;h=486&amp;store=1&amp;accept=image%2F*&amp;auth=LCA%20dc23cf68cd30de70689287f279b05b96e90103d9ea78c6ab7f28983e1f652ca6-ts%3D1734375546" alt /></p>
<p>In this system broker tells Booking to hold a ticket and it asks the payment to process a payment. Booking system does not know about the existence of Payment system. The broker will check the results of payment and ask booking to do whatever that needs to be done. Broker will also decide what email communication needs to be sent out.</p>
<p>Conductor pattern is useful in cases where the communication logic might be changing often and is far too critical to be left to distributed systems to implement correctly.</p>
<p><strong>Pros:</strong></p>
<ol>
<li><p>You have all the flow logic at single place</p>
</li>
<li><p>Debugging is easier</p>
</li>
<li><p>Bug detection is easier</p>
</li>
</ol>
<p><strong>Cons:</strong></p>
<ol>
<li><p>Conductor is a single point of failure</p>
</li>
<li><p>Conductor code gets complex with time</p>
</li>
<li><p>Scalability has challenges</p>
</li>
</ol>
<h2 id="heading-why-use-saga-at-all">Why use Saga at all ?</h2>
<p>Nearly all modern highly scalable systems end up using Saga pattern in some form for at least some of their problems. Saga’s benefits are that you do not have to rely on any long held locks. You can scale or rearchitect each system independently while keeping them loosely coupled.</p>
<p>Modern business needs are often a good justification as businesses often are run as complex long running processes involving multiple events.</p>
<p>To give you more context we have a deep dive into Saga pattern here.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=zu9aFuJ0iNQ">https://www.youtube.com/watch?v=zu9aFuJ0iNQ</a></div>
]]></content:encoded></item><item><title><![CDATA[Zero shot vs multi shot prompting?]]></title><description><![CDATA[One way to build classifiers in past was to provide a large number of examples to the model and let model train through some kind of training algorithm. Such training is complex and time consuming.
Large language models are massive and have learned a...]]></description><link>https://blog.principle-ai.com/zero-shot-vs-multi-shot-prompting</link><guid isPermaLink="true">https://blog.principle-ai.com/zero-shot-vs-multi-shot-prompting</guid><category><![CDATA[AI]]></category><dc:creator><![CDATA[Tanvi Nadkarni]]></dc:creator><pubDate>Sun, 15 Dec 2024 17:29:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1734283741290/15142850-496e-4216-b3c2-1008fbf933f1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>One way to build classifiers in past was to provide a large number of examples to the model and let model train through some kind of training algorithm. Such training is complex and time consuming.</p>
<p>Large language models are massive and have learned a lot of patterns. This can be leveraged to simplify the process of training a new model. Instead of training a new model from scratch, you can give a LLM some examples on the fly and the model is able to learn the patterns from those few examples. The speed comes from the fact that LLMs are trained on massive amount of data and have learned the “meta skill” of learning from patterns.</p>
<pre><code class="lang-plaintext">
Given these examples

Jon,13 to { "name": "Jon", "age":12 }

Emma,9 to { "name": "Emma", "age":9 }

Convert

Roger, 14
</code></pre>
<p>Nearly any LLM today can learn from this and give you the following answer.  </p>
<pre><code class="lang-plaintext">{ "name": "Roger", "age": 14 }
</code></pre>
<p>Doing the same with traditional models would be reasonably hard for open ended json parsing.</p>
<p>Even though example of multi-shot prompting here is simplistic this works pretty well even for more complex systems including cases were humans themselves might not be able to see the real conversion logic.</p>
<p>Models like Gemini can support upto 1M tokens. This is a very large context window and allows for many multi-shot examples.</p>
<blockquote>
<p>Zero-shot learning and few-shot learning represent two ends of the spectrum in LLM optimization. Zero-shot learning operates purely on the general knowledge acquired during pre-training, requiring no additional task-specific data. While this approach is advantageous for its efficiency and simplicity, it often struggles with tasks that require a nuanced understanding of domain-specific information. [<a target="_blank" href="https://medium.com/@zbabar/optimizing-large-language-models-using-multi-shot-learning-9ee9eb98709b#:~:text=By%20extending%20the%20principles%20of,powerful%20approach%20to%20improving%20model">source</a>]</p>
</blockquote>
<p>Zero shot prompting relies only on the the embedded logic of the LLM. It is not necessarily the bad idea to rely on the embedded logic of the LLM. Since LLMs have been trained on lot of existing data, they might be better than your examples to generate certain type of outputs.</p>
<pre><code class="lang-plaintext">Can you generate shells command to find the string "foo" 
and replace it with "bar" everywhere in a text file ?
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">sed -i 's/foo/bar/g' your_file.txt
</code></pre>
<p>Or translation</p>
<pre><code class="lang-plaintext">Convert “hello” to Spanish.
</code></pre>
<p><a target="_blank" href="https://aiauthority.dev/one-shot-vs-multi-shot-prompting">Zero shot is applicable</a> when you don’t actually have examples to provide nor you want your model to be constrained by any specific examples.</p>
<h2 id="heading-applying-few-shot-prompting-in-real-world-applications">Applying few shot prompting in real world applications</h2>
<p>One great way to apply few shot prompting in real world is customer success scenarios. Given 1000 examples of last resolves customer complains, can we predict what might be the solution to the incoming customer complaint or can we match the customer with the right service representative ?</p>
<p>Note that choice of examples in few shot is of paramount importance. If you give wrong and irrelevant examples your precision and recall goes down. So you need to carefully design your prompts.</p>
<p>Another example is e-commerce product recommendations. Last 1000 customers’s purchases looked like this. If a person has following 10 items in his cart recommend another product they should add to their cart.</p>
<p>Historically we used collaborative filtering to solve such recommendation problems.</p>
<p><strong>References:</strong></p>
<ol>
<li><p><a target="_blank" href="https://aiauthority.dev/one-shot-vs-multi-shot-prompting">https://aiauthority.dev/one-shot-vs-multi-shot-prompting</a></p>
</li>
<li><p><a target="_blank" href="https://labelbox.com/guides/zero-shot-learning-few-shot-learning-fine-tuning/">https://labelbox.com/guides/zero-shot-learning-few-shot-learning-fine-tuning/</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Designing a notification system]]></title><description><![CDATA[This is an interesting system design problem. Often this question gets asked in the context of delivery and the answer to that is relatively simple. Delivering notifications involve calling Apple and Google endpoints. This is failure prone and hence ...]]></description><link>https://blog.principle-ai.com/designing-a-notification-system</link><guid isPermaLink="true">https://blog.principle-ai.com/designing-a-notification-system</guid><category><![CDATA[System Architecture]]></category><category><![CDATA[interview]]></category><dc:creator><![CDATA[Tanvi Nadkarni]]></dc:creator><pubDate>Sun, 15 Dec 2024 07:52:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1734248670659/8677616a-e097-4c8b-a41c-51f0e9c41b86.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This is an interesting system design problem. Often this question gets asked in the context of delivery and the answer to that is relatively simple. Delivering notifications involve calling Apple and Google endpoints. This is failure prone and hence should be done as retriable async jobs. One of the solution is just to put it into a message queue meant for each of the services and let some dumb workers simply call the Apple and Google endpoints to deliver these notifications.</p>
<p>But this problem is not just about delivery but rather also the design. In a e-commerce company, there are multiple types of notifications. One set is critical notifications such as OTPs, Password recovery, Payment info, Delivery info etc. Another set of notifications could be marketing notifications based on complex scenarios. Different teams might want to create different type of “campaigns” to send notifications through various channels. Doing A/B tests with these notifications should also be possible.</p>
<p>To solve this problem we propose a Campaign Management System where such teams can design campaigns and set targeting criteria based on ETL events and other properties. An evaluation service that matches users with campaigns and schedules notifications.</p>
<p>A rendering engine is responsible for templates being converted into actual payload.</p>
<p>Finally a criteria engine ensures that the criteria is matched during delivery time right before final delivery.</p>
<p>We have done a in depth deep dive on this topic in the following video:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=EN4u_QLi168">https://www.youtube.com/watch?v=EN4u_QLi168</a></div>
]]></content:encoded></item><item><title><![CDATA[Asynchronous Communication in system designs]]></title><description><![CDATA[Async communication is one of the most important aspect of any complex system. Nearly all system design questions I have encountered in the wild have used this pattern in some form.
To understand what async communication is you need to understand wha...]]></description><link>https://blog.principle-ai.com/asynchronous-communication-in-system-designs</link><guid isPermaLink="true">https://blog.principle-ai.com/asynchronous-communication-in-system-designs</guid><category><![CDATA[System Design]]></category><dc:creator><![CDATA[Tanvi Nadkarni]]></dc:creator><pubDate>Sat, 07 Dec 2024 22:40:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1733610665183/ed8b1a27-9cb2-4a96-bd09-4314d7fa7d88.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Async communication is one of the most important aspect of any complex system. Nearly all system design questions I have encountered in the wild have used this pattern in some form.</p>
<p>To understand what async communication is you need to understand what it is really useful for. Our systems often consist of flows that involve multiple steps. For example, fetch a sitemap and then crawl thousands of pages in the sitemap. Then index those pages. Each of that step has a preceding step. But those steps also independent in a sense, first step just fetches the sitemap. It does not really care what happens after it. The second step cares about the sitemap but not how the sitemap was fetched.</p>
<p>In many synchronous flows such as say money transfer, each step is linked to other steps. For example you withdraw money from sender’s account and then deposit in receivers account. Together this is called a money movement transaction. Second step can not happen unless first step has happened and the first step must also be failed if second step fails. This is called synchronous flows.</p>
<p>Asynchronous communication is achieved using two primary architectural components. Firstly, message queues and second id pub/sub interface. Pub/Sub interface ultimately is designed using message queues and can be seen as an abstraction on top of message queue.</p>
<p>We have done this video to explain to you how message queue based async communication works.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=8moVErQn6LM">https://www.youtube.com/watch?v=8moVErQn6LM</a></div>
<p> </p>
<p>Please subscribe to our newsletter to stay updated with every new tutorial or major video we make.</p>
<p>If you need us to make a video about any specific system design problem do write us an email.</p>
]]></content:encoded></item><item><title><![CDATA[System Design : Feature Flag System]]></title><description><![CDATA[https://www.youtube.com/watch?v=Uoxje_Fnb0I
 
https://www.youtube.com/watch?v=nMQXXN8U7F0]]></description><link>https://blog.principle-ai.com/system-design-feature-flag-system</link><guid isPermaLink="true">https://blog.principle-ai.com/system-design-feature-flag-system</guid><category><![CDATA[System Design]]></category><dc:creator><![CDATA[Tanvi Nadkarni]]></dc:creator><pubDate>Sat, 30 Nov 2024 18:07:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1733610540898/f1e3a352-c1d0-466b-818b-14d8b5c25b1b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=Uoxje_Fnb0I">https://www.youtube.com/watch?v=Uoxje_Fnb0I</a></div>
<p> </p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=nMQXXN8U7F0">https://www.youtube.com/watch?v=nMQXXN8U7F0</a></div>
]]></content:encoded></item></channel></rss>