<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Debug School: rakesh kumar</title>
    <description>The latest articles on Debug School by rakesh kumar (@rakeshdevcotocus_468).</description>
    <link>https://www.debug.school/rakeshdevcotocus_468</link>
    <image>
      <url>https://www.debug.school/images/WnjM0tj_qJIv1YRaHUFCcWCxLQyroc-__BJWYYD46DE/rs:fill:90:90/g:sm/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvdXNl/ci9wcm9maWxlX2lt/YWdlLzkvMzhjZTM3/NDAtZDA2NC00MmVh/LTk1MmMtODg2MGQ2/MGNhZGU1LmpwZWc</url>
      <title>Debug School: rakesh kumar</title>
      <link>https://www.debug.school/rakeshdevcotocus_468</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://www.debug.school/feed/rakeshdevcotocus_468"/>
    <language>en</language>
    <item>
      <title>Different kind of prompt used by Spring AI</title>
      <dc:creator>rakesh kumar</dc:creator>
      <pubDate>Fri, 27 Mar 2026 06:17:45 +0000</pubDate>
      <link>https://www.debug.school/rakeshdevcotocus_468/different-kind-of-prompt-used-by-spring-ai-1o3j</link>
      <guid>https://www.debug.school/rakeshdevcotocus_468/different-kind-of-prompt-used-by-spring-ai-1o3j</guid>
      <description>&lt;p&gt;Main kinds of prompts Spring AI helps you make&lt;br&gt;
A. &lt;strong&gt;System prompt&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This tells the model how to behave.&lt;/p&gt;

&lt;p&gt;Examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;“You are a helpful banking assistant.”
“Answer in simple English.”
“Do not return unsafe medical advice.”
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Role: controls tone, style, rules, and boundaries. Spring AI docs say system messages are generated by the system to guide the conversation.&lt;/p&gt;

&lt;p&gt;B. &lt;strong&gt;User prompt&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is the actual question or request from the user.&lt;/p&gt;

&lt;p&gt;Examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;“What is compound interest?”
“Summarize this document.”
“Translate this to Hindi.”
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Role: carries the direct input to the model. Spring AI identifies user messages as the direct inputs from the user.&lt;/p&gt;

&lt;p&gt;C. &lt;strong&gt;Multi-message chat prompt&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This combines multiple messages together, usually:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;one or more system messages
one user message
sometimes previous conversation messages
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Role: gives the model better context than a single plain text prompt. Spring AI’s prompt model is message-based, not just one raw string.&lt;/p&gt;

&lt;p&gt;D. &lt;strong&gt;Template prompt / parameterized prompt&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is a prompt with placeholders like {name}, {topic}, {question}.&lt;/p&gt;

&lt;p&gt;Examples:&lt;/p&gt;

&lt;p&gt;“Explain {topic} to a beginner.”&lt;br&gt;
“Write an email to {customerName} about {issue}.”&lt;/p&gt;

&lt;p&gt;Role: makes prompts reusable and dynamic. The docs note that prompts often contain placeholders substituted at runtime. The prompt docs also compare this to a view template or SQL with placeholders.&lt;/p&gt;

&lt;p&gt;E. &lt;strong&gt;External file prompt&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can keep prompts outside Java code in template files instead of hardcoding them. That makes them reusable and easier to version and maintain. Your screenshot mentions .st, .mustache, and .ftl, and Spring AI’s docs show PromptTemplate rendering support, including the default StPromptTemplate based on StringTemplate.&lt;/p&gt;

&lt;p&gt;F. &lt;strong&gt;RAG prompt&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is used when you want the model to answer using retrieved context from documents or a vector database. Spring AI’s RAG support lets you customize a PromptTemplate that merges the user query with retrieved context, and the docs specify placeholders such as query and question_answer_context.&lt;/p&gt;

&lt;p&gt;G. &lt;strong&gt;Memory-aware prompt&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;LLMs are stateless by default, so Spring AI adds chat memory features to carry useful prior context into later interactions. This helps create prompts that include conversation context without you manually rebuilding it each time.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2) Why these prompt types matter&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Different prompt types solve different problems:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;System prompt → behavior and rules
User prompt → actual request
Template prompt → reuse and dynamic input
RAG prompt → answer from documents/context
Memory-aware prompt → continue a conversation naturally
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That is why Spring AI is useful: it gives structure around prompt creation instead of making you manually assemble raw HTTP JSON every time. ChatClient builds prompt parts fluently, and Advisors can add memory, retrieved documents, and more advanced behavior.&lt;/p&gt;

&lt;p&gt;3) Coding examples&lt;/p&gt;

&lt;p&gt;These examples are written in the normal Spring AI style and may need small adjustment depending on your exact Spring AI version.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1: Simple system prompt + user prompt&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@RestController
@RequestMapping("/ai")
public class ChatController {

    private final ChatClient chatClient;

    public ChatController(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    @GetMapping("/explain")
    public String explain(@RequestParam String topic) {
        return chatClient.prompt()
                .system("You are a Java teacher. Explain in simple English.")
                .user("Explain this topic for a beginner: {topic}")
                .param("topic", topic)
                .call()
                .content();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What happens here&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.system(...) creates a system prompt
.user(...) creates a user prompt
.param(...) fills the template placeholder dynamically
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This matches the docs’ message-based prompt model and runtime placeholder substitution.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 2: Reusable template prompt&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Service
public class EmailPromptService {

    private final ChatClient chatClient;

    public EmailPromptService(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    public String generateEmail(String customerName, String issue) {
        return chatClient.prompt()
                .system("You are a professional customer support writer.")
                .user("""
                      Write a polite support email to {customerName}.
                      The issue is: {issue}
                      Keep the tone professional and short.
                      """)
                .param("customerName", customerName)
                .param("issue", issue)
                .call()
                .content();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Why this is useful&lt;/p&gt;

&lt;p&gt;Same prompt structure, different values. That is the main idea of template prompts. Spring AI docs explicitly describe placeholders being replaced based on user requests or application code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 3: Prompt from external template file idea&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Suppose you keep a prompt file like:&lt;/p&gt;

&lt;p&gt;src/main/resources/prompts/greeting.st&lt;/p&gt;

&lt;p&gt;Hello, my name is {name}. Can you greet me back nicely?&lt;/p&gt;

&lt;p&gt;Then your code can render and send it through Spring AI. A simplified example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Service
public class GreetingService {

    private final ChatClient chatClient;

    public GreetingService(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    public String greet(String name) {
        String template = "Hello, my name is {name}. Can you greet me back nicely?";

        return chatClient.prompt()
                .user(template)
                .param("name", name)
                .call()
                .content();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Spring AI supports prompt templating and documents PromptTemplate; for RAG templates it uses StPromptTemplate by default, based on StringTemplate.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 4: RAG-style prompt&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;String answer = chatClient.prompt()
        .system("Answer only from the provided context. If unsure, say you do not know.")
        .user("""
              Question: {question}

              Context:
              {context}
              """)
        .param("question", "What is the refund policy?")
        .param("context", """
                Refunds are allowed within 7 days of purchase
                if the product has not been activated.
                """)
        .call()
        .content();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the basic idea behind a RAG prompt: merge the user query with retrieved context. Spring AI’s RAG docs describe custom templates that combine query and retrieved context for answering.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 5: Memory-aware chat idea&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;String response = chatClient.prompt()
        .system("You are a helpful assistant that remembers prior discussion context.")
        .user("Continue our last discussion and summarize the final decision.")
        .call()
        .content();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In real apps, chat memory is usually backed by Spring AI chat memory support, because LLMs are stateless by default and Spring AI adds memory abstractions to maintain useful context.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.debug.school/images/ICe4A002KxlSMhQ7niFzTjYFqMi_0lTB3IjFZt6SMdk/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvajFzeGUy/NmNqeG93NTkwNHl0/a2wucG5n" class="article-body-image-wrapper"&gt;&lt;img src="https://www.debug.school/images/ICe4A002KxlSMhQ7niFzTjYFqMi_0lTB3IjFZt6SMdk/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvajFzeGUy/NmNqeG93NTkwNHl0/a2wucG5n" alt=" " width="632" height="703"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Very simple summary
&lt;/h2&gt;

&lt;p&gt;Spring AI mainly helps you create these prompt types:&lt;/p&gt;

&lt;p&gt;System prompts&lt;br&gt;
User prompts&lt;br&gt;
Multi-message prompts&lt;br&gt;
Template prompts&lt;br&gt;
External-file prompts&lt;br&gt;
RAG prompts&lt;br&gt;
Memory-aware prompts&lt;/p&gt;

&lt;p&gt;So the big benefit is not just “send text to GPT.”&lt;br&gt;
The real benefit is: Spring AI gives prompt structure, reuse, context, and maintainability inside a Spring Boot application&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How Spring AI Simplifies REST API Integration in Modern Applications</title>
      <dc:creator>rakesh kumar</dc:creator>
      <pubDate>Fri, 27 Mar 2026 05:30:34 +0000</pubDate>
      <link>https://www.debug.school/rakeshdevcotocus_468/how-spring-ai-simplifies-rest-api-integration-in-modern-applications-2l5c</link>
      <guid>https://www.debug.school/rakeshdevcotocus_468/how-spring-ai-simplifies-rest-api-integration-in-modern-applications-2l5c</guid>
      <description>&lt;p&gt;&lt;strong&gt;Theory explanation&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Why not call REST API directly from controller?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Main purpose of Spring AI interface&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Why this helps in modern applications&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Simple flow&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Coding example&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Theory explanation
&lt;/h2&gt;

&lt;p&gt;In a normal Spring Boot project, you can call an AI provider directly with REST APIs.&lt;br&gt;
That means your code builds HTTP requests, adds headers, sends JSON, handles authentication, parses responses, and manages retries by itself.&lt;/p&gt;

&lt;p&gt;That works for small demos, but in modern applications it becomes repetitive and hard to maintain.&lt;/p&gt;

&lt;p&gt;Spring AI simplifies this by putting a Spring-style abstraction layer between your application and the AI provider. Instead of writing low-level HTTP code everywhere, you work with higher-level APIs such as ChatClient, ChatModel, Prompt, and advisors. The Spring AI reference describes ChatClient as a fluent API for communicating with an AI model, where prompts are built from messages like user and system messages.&lt;/p&gt;

&lt;p&gt;So the difference is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;REST API only = low-level transport and manual integration
Spring AI = structured, reusable, Spring-friendly AI integration built on top of provider APIs
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Why not call REST API directly from controller?
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Because controller should mainly handle:&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;incoming request
validation
response

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;If controller also manages:&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;AI API payloads
prompt structure
JSON parsing
retries
embeddings
vector DB lookup
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://www.debug.school/images/9hbPDkP6r2Gl5J8i7l9u6_i1Dxb-LPpYTDmd--0F2uI/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvY3h3d2t2/YmV1cDZrMXUxcHg1/NGIucG5n" class="article-body-image-wrapper"&gt;&lt;img src="https://www.debug.school/images/9hbPDkP6r2Gl5J8i7l9u6_i1Dxb-LPpYTDmd--0F2uI/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvY3h3d2t2/YmV1cDZrMXUxcHg1/NGIucG5n" alt=" " width="453" height="593"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;then controller becomes overloaded.&lt;/p&gt;

&lt;p&gt;Spring AI keeps the design cleaner.&lt;br&gt;
&lt;a href="https://www.debug.school/images/ojHOMRmwwKQKQczz2ElO1MPlZiLxFg9nYrHaURwUetg/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvbDVjM2ht/bzV5eWEyNGRlaHln/dmIucG5n" class="article-body-image-wrapper"&gt;&lt;img src="https://www.debug.school/images/ojHOMRmwwKQKQczz2ElO1MPlZiLxFg9nYrHaURwUetg/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvbDVjM2ht/bzV5eWEyNGRlaHln/dmIucG5n" alt=" " width="715" height="277"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Main purpose of Spring AI interface
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;It hides low-level HTTP complexity&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You do not need to manually build every REST request.&lt;/p&gt;

&lt;p&gt;Instead of this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;create URL
create headers
add API key
build JSON
send request
parse result
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can use a cleaner Spring-style approach.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;It gives a Spring-friendly programming model&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In Spring Boot, developers like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dependency injection
beans
service classes
reusable configuration
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Spring AI fits that style.&lt;/p&gt;

&lt;p&gt;So AI feels like a normal Spring service, not like raw external API handling.&lt;/p&gt;

&lt;p&gt;Example idea:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ChatClient
EmbeddingModel
PromptTemplate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These are easier to use in service classes.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;It reduces vendor lock-in&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Different providers have different request and response formats.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Without Spring AI:&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;OpenAI code looks one way
another provider looks different
switching providers means code change in many places
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;With Spring AI&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;you work through a common abstraction
changing provider becomes easier
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;It supports AI-specific features, not just REST calling&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;AI integration is not just sending text over HTTP.&lt;/p&gt;

&lt;p&gt;It often includes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;prompt templating
chat memory
embeddings
vector search
RAG flow
structured output
model options
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;REST API does not give these patterns automatically.&lt;/p&gt;

&lt;p&gt;Spring AI provides structure for them.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;It makes enterprise code cleaner&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In small demo projects, direct REST calls are okay.&lt;/p&gt;

&lt;p&gt;But in real applications:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;chatbot
recommendation engine
support assistant
document Q&amp;amp;A
healthcare AI assistant
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;you need better architecture.&lt;/p&gt;

&lt;p&gt;Spring AI helps separate:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;controller
business logic
AI interaction
prompt layer
retrieval layer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That makes the project easier to scale.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why this helps in modern applications
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Cleaner code&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Without Spring AI, you often repeat:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;API URL handling
auth token or API key setup
request body creation
response parsing
provider-specific JSON mapping
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Spring AI centralizes that interaction. Its model API is designed as a portable interface across providers, which makes the code cleaner and more maintainable.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Easier provider switching&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you call one provider directly using raw REST, your code usually becomes tightly coupled to that provider’s request and response format.&lt;/p&gt;

&lt;p&gt;Spring AI’s Chat Model API is designed to be portable, so moving across supported providers requires fewer code changes than rewriting raw REST integration everywhere.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Prompt handling becomes structured&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Modern AI apps need more than one plain input string. They need:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;system instructions
user prompts
templates
placeholders
context injection
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Spring AI supports prompts as structured message collections and supports prompt templating, which is much better than building JSON strings manually for each REST call.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Better support for advanced AI patterns&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Modern applications often need:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;chat memory
embeddings
RAG
tool calling
streaming responses
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Spring AI supports these patterns directly through its APIs and advisors, which is far beyond “just send a REST request.”&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Better fit with Spring Boot architecture&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Spring developers prefer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dependency injection
beans
service classes
configuration properties
starter-based setup
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Spring AI fits naturally into that model. For example, the official docs provide Spring Boot starter-based configuration such as spring-ai-starter-model-openai, and the getting-started docs state support for Spring Boot 3.4.x and 3.5.x.&lt;/p&gt;

&lt;h2&gt;
  
  
  Simple flow
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Direct REST approach&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Controller → Service → Manual HTTP Client → AI Provider API
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Spring AI approach&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Controller → Service → ChatClient / ChatModel → AI Provider API
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Spring AI still uses provider APIs underneath, but your application code stays much simpler.&lt;/p&gt;

&lt;h2&gt;
  
  
  Coding example
&lt;/h2&gt;

&lt;p&gt;Below is a simple Spring Boot example using Spring AI with OpenAI-style integration.&lt;/p&gt;

&lt;p&gt;1) &lt;strong&gt;Maven dependencies&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependencyManagement&amp;gt;
    &amp;lt;dependencies&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.springframework.ai&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;spring-ai-bom&amp;lt;/artifactId&amp;gt;
            &amp;lt;version&amp;gt;YOUR_VERSION&amp;lt;/version&amp;gt;
            &amp;lt;type&amp;gt;pom&amp;lt;/type&amp;gt;
            &amp;lt;scope&amp;gt;import&amp;lt;/scope&amp;gt;
        &amp;lt;/dependency&amp;gt;
    &amp;lt;/dependencies&amp;gt;
&amp;lt;/dependencyManagement&amp;gt;

&amp;lt;dependencies&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.ai&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-ai-starter-model-openai&amp;lt;/artifactId&amp;gt;
    &amp;lt;/dependency&amp;gt;

    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-boot-starter-web&amp;lt;/artifactId&amp;gt;
    &amp;lt;/dependency&amp;gt;
&amp;lt;/dependencies&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The official Spring AI OpenAI chat docs show spring-ai-starter-model-openai as the starter artifact.&lt;/p&gt;

&lt;p&gt;2) &lt;strong&gt;application.properties&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;spring.ai.openai.api-key=YOUR_API_KEY
spring.ai.openai.chat.options.model=gpt-4o-mini
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Spring AI provides Spring Boot auto-configuration for the OpenAI chat client through properties under the Spring AI namespace.&lt;/p&gt;

&lt;p&gt;3) &lt;strong&gt;Service class&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.demo.service;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;

@Service
public class AiService {

    private final ChatClient chatClient;

    public AiService(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    public String explainTopic(String topic) {
        return chatClient.prompt()
                .system("You are a helpful Java and Spring expert. Explain in simple English.")
                .user("Explain this topic in a modern application context: {topic}")
                .param("topic", topic)
                .call()
                .content();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This uses ChatClient’s fluent API to build a prompt from system and user messages, with runtime parameters. That is exactly the sort of prompt-building model described in the official docs.&lt;/p&gt;

&lt;p&gt;4) &lt;strong&gt;REST controller&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.example.demo.controller;

import com.example.demo.service.AiService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AiController {

    private final AiService aiService;

    public AiController(AiService aiService) {
        this.aiService = aiService;
    }

    @GetMapping("/api/explain")
    public String explain(@RequestParam String topic) {
        return aiService.explainTopic(topic);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now your application exposes a normal REST endpoint, but internally it uses Spring AI rather than a manually coded HTTP call to the model provider.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.debug.school/images/9dZjWh6b4U7oicTYDGqu_GFiJ_q7TSaptCcfJoLOKpc/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvamhsMHBr/MTk1OXNpcWwxMDZ6/eTQucG5n" class="article-body-image-wrapper"&gt;&lt;img src="https://www.debug.school/images/9dZjWh6b4U7oicTYDGqu_GFiJ_q7TSaptCcfJoLOKpc/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvamhsMHBr/MTk1OXNpcWwxMDZ6/eTQucG5n" alt=" " width="342" height="697"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How to integrate AI models into Spring Boot applications using Spring AI</title>
      <dc:creator>rakesh kumar</dc:creator>
      <pubDate>Fri, 27 Mar 2026 03:39:18 +0000</pubDate>
      <link>https://www.debug.school/rakeshdevcotocus_468/how-to-integrate-ai-models-into-spring-boot-applications-using-spring-ai-amp</link>
      <guid>https://www.debug.school/rakeshdevcotocus_468/how-to-integrate-ai-models-into-spring-boot-applications-using-spring-ai-amp</guid>
      <description>&lt;p&gt;&lt;strong&gt;What is Spring AI?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Spring AI Architecture&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Purpose of Spring AI&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Role of Spring AI&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;How Flow Works&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Common Questions (with Answers)&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  What is Spring AI?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://www.debug.school/images/_-xR9Nw_BnWWUecHPUpfYtdUlRLgeTEu2NlClfK0dzs/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvNGl6Y25i/aWVmbDJwcjl4bWFt/N3EucG5n" class="article-body-image-wrapper"&gt;&lt;img src="https://www.debug.school/images/_-xR9Nw_BnWWUecHPUpfYtdUlRLgeTEu2NlClfK0dzs/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvNGl6Y25i/aWVmbDJwcjl4bWFt/N3EucG5n" alt=" " width="688" height="391"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Spring AI is a framework that helps developers integrate AI models (like GPT, LLMs, embeddings, etc.) into Spring Boot applications easily.&lt;/p&gt;

&lt;p&gt;Instead of manually calling AI APIs and handling complexity, Spring AI provides:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Clean Java-based abstraction
Easy integration with AI providers (OpenAI, Azure, etc.)
Support for chat, embeddings, vector DB, prompt templates
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;👉 In simple words:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Spring AI = Bridge between Spring Boot apps and AI models
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;🎯 &lt;/p&gt;

&lt;h2&gt;
  
  
  Spring AI Architecture
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://www.debug.school/images/Xs3VJf5GJv7PQ0BX1A9MHBi3eOcTOLWs-NC4iw70vU8/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvYjUxMGtw/cXpvNWcwNHl5emE0/aDEucG5n" class="article-body-image-wrapper"&gt;&lt;img src="https://www.debug.school/images/Xs3VJf5GJv7PQ0BX1A9MHBi3eOcTOLWs-NC4iw70vU8/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvYjUxMGtw/cXpvNWcwNHl5emE0/aDEucG5n" alt=" " width="800" height="351"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How Spring AI Works&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Users give input to Spring Boot REST controller.&lt;/li&gt;
&lt;li&gt;Spring AI  processes the user input using Prompt Templates or ChatClient (to call LLM)&lt;/li&gt;
&lt;li&gt;ChatClient connects to external AI providers (OpenAI, Ollama, etc.)&lt;/li&gt;
&lt;li&gt;And response is returned to the Spring Boot app and sent back to the user
. 
&lt;strong&gt;Multi-Provider Support&lt;/strong&gt;: Spring AI framework supports connecting to multiple LLM providers like
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;OpenAI (ChatGPT)
Azure OpenAI
Hugging Face (Transformers)
Ollama (for local models)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Chat Client API&lt;/strong&gt;: Standardizes communication with LLMs using a fluent API, regardless of provider differences.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prompt Templates&lt;/strong&gt;: Developers can define dynamic prompts with variables using Spring Expression Language (SpEL).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Embedding and Vector Store Integration&lt;/strong&gt;: Spring AI supports converting text into embeddings like numeric vector and storing them in vector databases like PostgreSQL with pgvector.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Structured Outputs ( Like POJO Mapping)&lt;/strong&gt;: Spring AI model output (like JSON) directly to the Java POJOs class using annotations and converters.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Features of Spring AI&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Purpose of Spring AI
&lt;/h2&gt;

&lt;p&gt;The main purpose is to simplify AI integration in enterprise Java applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Goals:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Reduce boilerplate code for AI API calls
Provide standardized APIs (like Spring Data, Spring MVC)
Enable production-ready AI apps
Support scalable and maintainable architecture
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;🧩 &lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.debug.school/images/FY8Np1unpTsJoihNjo8zyy6EaqZaRgkMqIHWU7sZSYI/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvOWJrc3U4/bG5mZ3FrbzEwOWN0/MTMucG5n" class="article-body-image-wrapper"&gt;&lt;img src="https://www.debug.school/images/FY8Np1unpTsJoihNjo8zyy6EaqZaRgkMqIHWU7sZSYI/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvOWJrc3U4/bG5mZ3FrbzEwOWN0/MTMucG5n" alt=" " width="800" height="550"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Role of Spring AI
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;AI Integration Layer&lt;/strong&gt;
Connects your Spring Boot app with AI models
Handles API calls, authentication, retries&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Abstraction Provider&lt;/strong&gt;
You don’t write raw HTTP calls
Use simple Java interfaces&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Prompt Management&lt;/strong&gt;
Helps structure prompts cleanly
Supports templates&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Data Handling (Vector + Embeddings)&lt;/strong&gt;
Store &amp;amp; search semantic data
Used in RAG (Retrieval-Augmented Generation)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Enterprise Enablement&lt;/strong&gt;
Works with microservices
Secure, scalable, production-ready
🏗️ Architecture (Colorful + Labeled Representation)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://www.debug.school/images/zNBH2tvUSYxle2_iBZkJi20nljpVu8jSIOd2_LMFm1c/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvbXF5N2Vq/amFoc3UwdDJiZnFz/MjEucG5n" class="article-body-image-wrapper"&gt;&lt;img src="https://www.debug.school/images/zNBH2tvUSYxle2_iBZkJi20nljpVu8jSIOd2_LMFm1c/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvbXF5N2Vq/amFoc3UwdDJiZnFz/MjEucG5n" alt=" " width="387" height="693"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  How Flow Works
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;User sends request → Frontend
Request hits → Spring Boot Controller
Service calls → Spring AI layer
Spring AI sends request → AI Model (GPT)
AI response → back to Spring Boot → UI
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;❓ &lt;/p&gt;

&lt;h2&gt;
  
  
  Common Questions (with Answers)
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Why use Spring AI instead of direct API calls?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;👉 Because it reduces complexity, gives structure, and is production-ready.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Can Spring AI work with Laravel backend?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;👉 No directly. Spring AI is for Java ecosystem.&lt;br&gt;
For Laravel, you use OpenAI SDK or HTTP APIs manually.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Is Spring AI suitable for microservices?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;👉 Yes, very suitable. You can create:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;AI microservice
Chat service
Recommendation engine
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;What features does Spring AI provide?&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Chat completion
Embeddings
Prompt templates
Vector DB integration
RAG support
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;When should you choose Spring AI?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;👉 Choose it when:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Your backend is Spring Boot
You need enterprise AI integration
You want clean, scalable architecture
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;When NOT to use Spring AI?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;👉 Avoid if:&lt;/p&gt;

&lt;p&gt;Your backend is Laravel/PHP&lt;br&gt;
Small project (simple API call enough)&lt;br&gt;
🔥 &lt;strong&gt;Final Simple Summary&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Purpose: Simplify AI integration
Role: Bridge Spring Boot ↔ AI Models
Benefit: Clean, scalable, enterprise-ready AI apps
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://medium.com/@0_bibhuti/spring-ai-build-intelligent-applications-with-ease-c3c28c7bb15d" rel="noopener noreferrer"&gt;Reference&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.youtube.com/watch?v=BFk_nAJapYc&amp;amp;list=PL0zysOflRCen1TeDUm-ebl9T-WbJygCGE&amp;amp;index=5" rel="noopener noreferrer"&gt;utube&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How to Build a Simple AI Question Answer App with LangChain</title>
      <dc:creator>rakesh kumar</dc:creator>
      <pubDate>Tue, 17 Mar 2026 10:35:28 +0000</pubDate>
      <link>https://www.debug.school/rakeshdevcotocus_468/how-to-build-a-simple-ai-question-answer-app-with-langchain-4cc9</link>
      <guid>https://www.debug.school/rakeshdevcotocus_468/how-to-build-a-simple-ai-question-answer-app-with-langchain-4cc9</guid>
      <description>&lt;p&gt;&lt;strong&gt;Direct LLM call&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;result = llm.invoke("What is generative AI?")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Chain call&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;chain = prompt | llm
response = chain.invoke({"input":"Can you tell me about Langsmith?"})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Chain with output parser&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;chain = prompt | llm | output_parser
response = chain.invoke({"input":"Can you tell me about Langsmith?"})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Why use chain?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We use a chain to connect multiple steps in one flow.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;first step = format the prompt

second step = send it to LLM

third step = parse the output
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So instead of writing everything separately, chain makes it clean, reusable, and easy to manage.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Simple sentence:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Chain is used to join prompt + model + parser into one pipeline.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why use StrOutputParser?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When you call:&lt;/p&gt;

&lt;p&gt;response = chain.invoke(...)&lt;/p&gt;

&lt;p&gt;&lt;code&gt;without parser, the output is usually an AIMessage object.&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;That means response contains:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;content

metadata

extra model information
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But many times we only need the final text.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;So StrOutputParser() converts the output into a plain string.&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Simple sentence:&lt;/p&gt;

&lt;p&gt;StrOutputParser is used to extract only text from the model response.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Difference between both chains&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Chain 1
chain = prompt | llm
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Output type:&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;AIMessage&lt;br&gt;
Chain 2&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;chain = prompt | llm | output_parser
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Output type:&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;str&lt;br&gt;
&lt;strong&gt;Why use second chain?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Because it gives clean text output, which is easier to:&lt;/p&gt;

&lt;p&gt;print&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;store in database

show in UI

pass to next function
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;20 Important Questions Based on Your Screenshot&lt;/p&gt;

&lt;h2&gt;
  
  
  Subjective Questions
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What is the purpose of load_dotenv() in this code?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Answer:&lt;br&gt;
load_dotenv() loads environment variables from the .env file into Python, so secrets like API keys can be used safely.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Why do we store OPENAI_API_KEY in environment variables?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Answer:&lt;br&gt;
Because API keys are sensitive data. Keeping them in environment variables is safer than writing them directly in code.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What is the use of ChatOpenAI(model="gpt-4o")?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Answer:&lt;br&gt;
It creates an LLM object that allows us to communicate with the OpenAI chat model.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What does llm.invoke("What is generative AI?") do?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Answer:&lt;br&gt;
It sends the input question to the model and gets a response back.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What is ChatPromptTemplate?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Answer:&lt;br&gt;
ChatPromptTemplate helps us create structured prompts using system messages and user messages.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Why do we use a system message in prompt template?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Answer:&lt;br&gt;
A system message sets the behavior of the model, like telling it to act as an AI engineer or teacher.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Why do we use {input} inside the prompt template?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Answer:&lt;br&gt;
{input} is a variable placeholder. It lets us send different user questions dynamically.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Why do we use prompt | llm?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Answer:&lt;br&gt;
It creates a chain where the prompt is first prepared and then sent to the language model automatically.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Why do we use StrOutputParser()?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Answer:&lt;br&gt;
Because the LLM normally returns an AIMessage object, and StrOutputParser() converts that into plain text.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What is the main benefit of using chains in LangChain?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Answer:&lt;br&gt;
Chains reduce manual coding and make the workflow modular, readable, and reusable.&lt;/p&gt;

&lt;h2&gt;
  
  
  Objective Questions
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;load_dotenv() is used to&lt;/strong&gt;:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Answer: Load variables from .env file.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;os.getenv("OPENAI_API_KEY") is used to:&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Answer: Read the API key from environment variables.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;The output type of prompt | llm is generally&lt;/strong&gt;:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Answer: AIMessage&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;The output type of prompt | llm | StrOutputParser() is generally&lt;/strong&gt;:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Answer: string&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;ChatPromptTemplate.from_messages() is used to&lt;/strong&gt;:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Answer: Create prompt structure using system and human messages.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;LANGCHAIN_TRACING_V2="true" is used for&lt;/strong&gt;:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Answer: Tracking and monitoring LangChain execution.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;The symbol | in LangChain is used to&lt;/strong&gt;:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Answer: Combine components into a chain.&lt;/p&gt;

&lt;h2&gt;
  
  
  MCQ Questions
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Which function loads environment variables from a .env file&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. getenv()&lt;br&gt;
B. load_dotenv()&lt;br&gt;
C. setenv()&lt;br&gt;
D. read_env()&lt;/p&gt;

&lt;p&gt;Answer: B. load_dotenv()&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What does StrOutputParser() return?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. JSON object&lt;br&gt;
B. Dictionary&lt;br&gt;
C. Plain text string&lt;br&gt;
D. AIMessage object&lt;/p&gt;

&lt;p&gt;Answer: C. Plain text string&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Why is prompt | llm | output_parser better than only prompt | llm in many cases?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. It increases API speed&lt;br&gt;
B. It converts response into plain text&lt;br&gt;
C. It removes API key&lt;br&gt;
D. It changes model version&lt;/p&gt;

&lt;p&gt;Answer: B. It converts response into plain text&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What is the role of PromptTemplate in this code?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. To create database models&lt;br&gt;
B. To define structured prompt text for the LLM&lt;br&gt;
C. To validate JSON request&lt;br&gt;
D. To start Flask server&lt;/p&gt;

&lt;p&gt;Answer: B. To define structured prompt text for the LLM&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which of the following is one of the prompt keys in the prompts dictionary?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. student_details&lt;br&gt;
B. recommendation&lt;br&gt;
C. save_recipe&lt;br&gt;
D. database_query&lt;/p&gt;

&lt;p&gt;Answer: B. recommendation&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;What is checked in this block?&lt;/strong&gt;
if llm is None:
return jsonify({"error": "LLM is not available"}), 500&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Whether query is empty&lt;br&gt;
B. Whether prompt is missing&lt;br&gt;
C. Whether language model instance is available&lt;br&gt;
D. Whether JSON is valid&lt;/p&gt;

&lt;p&gt;Answer: C. Whether language model instance is available&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What does status code 500 mean here?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Data created successfully&lt;br&gt;
B. Redirect response&lt;br&gt;
C. Internal server error&lt;br&gt;
D. Unauthorized user&lt;/p&gt;

&lt;p&gt;Answer: C. Internal server error&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;What is created by this line?&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;chains = {key: prompts[key] | llm for key in selected_chains}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A. A database connection&lt;br&gt;
B. A dictionary of runnable chains for selected prompts&lt;br&gt;
C. A list of user queries&lt;br&gt;
D. A JSON response&lt;/p&gt;

&lt;p&gt;Answer: B. A dictionary of runnable chains for selected prompts&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;What does the | operator do in this line?&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;prompts[key] | llm
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A. Performs bitwise OR&lt;br&gt;
B. Joins prompt template with LLM into a pipeline/chain&lt;br&gt;
C. Compares two values&lt;br&gt;
D. Converts string to JSON&lt;/p&gt;

&lt;p&gt;Answer: B. Joins prompt template with LLM into a pipeline/chain&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Why is RunnableParallel(&lt;/strong&gt;chains) used?**&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. To execute all selected chains one after another very slowly&lt;br&gt;
B. To run multiple selected chains in parallel&lt;br&gt;
C. To save results in database&lt;br&gt;
D. To validate prompt variables&lt;/p&gt;

&lt;p&gt;Answer: B. To run multiple selected chains in parallel&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;What does this line do?&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;results = parallel_chain.invoke({"query": query})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A. Deletes the query&lt;br&gt;
B. Executes the chains using the given query input&lt;br&gt;
C. Stops the LLM&lt;br&gt;
D. Creates a new route&lt;/p&gt;

&lt;p&gt;Answer: B. Executes the chains using the given query input&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;What is the main purpose of this loop?&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for key, value in results.items():
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A. To create database tables&lt;br&gt;
B. To process each chain output one by one&lt;br&gt;
C. To remove invalid prompts&lt;br&gt;
D. To sort the JSON request&lt;/p&gt;

&lt;p&gt;Answer: B. To process each chain output one by one&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Why is this line used?&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;content = value.content if hasattr(value, "content") else str(value)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A. To check whether output has a content attribute and extract text safely&lt;br&gt;
B. To delete content from result&lt;br&gt;
C. To convert list into dictionary&lt;br&gt;
D. To validate selected chains&lt;/p&gt;

&lt;p&gt;Answer: A. To check whether output has a content attribute and extract text safely&lt;/p&gt;

&lt;p&gt;Extra Important Interview Questions From This Screenshot&lt;/p&gt;

&lt;p&gt;Here are some more commonly asked short questions you can revise:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Why not call the model directly every time?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Because direct model calls are fine for simple tasks, but chains are better for structured and reusable workflows.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Why use prompt templates instead of raw strings&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Because prompt templates are dynamic, cleaner, and easier to reuse.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What happens if we do not use output parser?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We get a model response object like AIMessage, not just plain text.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;When is StrOutputParser very useful?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;It is useful when you want only final text for display, saving, or passing to another function.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Why is chain more scalable?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Because later you can add memory, retrievers, tools, parsers, and multiple steps easily.&lt;/p&gt;

&lt;h2&gt;
  
  
  One-line easy revision
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;LLM gives response

Prompt template formats input

Chain connects steps

StrOutputParser extracts plain text
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>How to apply Persistent Login to Secure Sessions in Rust</title>
      <dc:creator>rakesh kumar</dc:creator>
      <pubDate>Fri, 06 Mar 2026 10:35:17 +0000</pubDate>
      <link>https://www.debug.school/rakeshdevcotocus_468/how-to-apply-persistent-login-to-secure-sessions-in-rust-32ga</link>
      <guid>https://www.debug.school/rakeshdevcotocus_468/how-to-apply-persistent-login-to-secure-sessions-in-rust-32ga</guid>
      <description>&lt;p&gt;Normally in web applications there are two types of login systems.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Session Login (Normal Login)&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;User logs in → session cookie created → session stored in server.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Problem&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;If browser closes → session expires

If server restarts → session lost
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;User must login again&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Persistent Login (Remember Me)&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Persistent login allows:&lt;/p&gt;

&lt;p&gt;User logs in → system stores secure token in database + cookie&lt;/p&gt;

&lt;p&gt;Even if:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;browser closes

session expires

server restarts
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;User can still be automatically logged in.&lt;/p&gt;

&lt;p&gt;So the purpose of persistent login is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Improve user experience

Reduce repeated login

Maintain security

Allow long-term authentication safely
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Add security env vars&lt;/strong&gt;&lt;br&gt;
Add security env vars: SESSION_KEY, SESSION_TTL_HOURS, SESSION_SECURE_COOKIE.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SESSION_KEY=replace-with-32-byte-random-secret
SESSION_TTL_HOURS=24
# In production behind HTTPS set true. Local HTTP dev can stay false.
SESSION_SECURE_COOKIE=false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Read and validate those env vars into AppConfig fields:&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;src/config.rs&lt;/code&gt;&lt;br&gt;
&lt;code&gt;Read and validate those env vars into AppConfig fields:&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;session_ttl_hours&lt;br&gt;
session_secure_cookie&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pub session_ttl_hours: i64,
pub session_secure_cookie: bool,
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   let session_ttl_hours = env::var("SESSION_TTL_HOURS")
            .ok()
            .and_then(|v| v.parse::&amp;lt;i64&amp;gt;().ok())
            .filter(|v| *v &amp;gt; 0)
            .unwrap_or(24);

        // Keep local dev usable on HTTP, default secure in non-local environments.
        let inferred_local = bind_addr.contains("127.0.0.1") || bind_addr.contains("localhost");
        let session_secure_cookie = env::var("SESSION_SECURE_COOKIE")
            .ok()
            .map(|v| {
                let lower = v.trim().to_ascii_lowercase();
                lower == "1" || lower == "true" || lower == "yes" || lower == "on"
            })
            .unwrap_or(!inferred_local);

        Self {
            app_name,
            bind_addr,
            database_url,
            session_ttl_hours,
            session_secure_cookie,
        }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;full code&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use std::env;

#[derive(Clone, Debug)]
pub struct AppConfig {
    pub app_name: String,
    pub bind_addr: String,
    pub database_url: String,
    pub session_ttl_hours: i64,
    pub session_secure_cookie: bool,
}

impl AppConfig {
    pub fn from_env() -&amp;gt; Self {
        let app_name = env::var("APP_NAME").unwrap_or_else(|_| "Rust CRUD Dashboard".to_string());
        let bind_addr = env::var("APP_BIND").unwrap_or_else(|_| "127.0.0.1:8080".to_string());
        let database_url = env::var("DATABASE_URL")
            .unwrap_or_else(|_| "mysql://root:@127.0.0.1:3306/rust_crud".to_string());
        let session_ttl_hours = env::var("SESSION_TTL_HOURS")
            .ok()
            .and_then(|v| v.parse::&amp;lt;i64&amp;gt;().ok())
            .filter(|v| *v &amp;gt; 0)
            .unwrap_or(24);

        // Keep local dev usable on HTTP, default secure in non-local environments.
        let inferred_local = bind_addr.contains("127.0.0.1") || bind_addr.contains("localhost");
        let session_secure_cookie = env::var("SESSION_SECURE_COOKIE")
            .ok()
            .map(|v| {
                let lower = v.trim().to_ascii_lowercase();
                lower == "1" || lower == "true" || lower == "yes" || lower == "on"
            })
            .unwrap_or(!inferred_local);

        Self {
            app_name,
            bind_addr,
            database_url,
            session_ttl_hours,
            session_secure_cookie,
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Apply session middleware hardening:&lt;/strong&gt;&lt;br&gt;
Apply session middleware hardening:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;custom cookie name
cookie_secure(...)
cookie_http_only(true)
session_lifecycle(PersistentSession...session_ttl...)
safer SESSION_KEY handling (no fixed default secret)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;src/main.rs&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Apply session middleware hardening:&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;custom cookie name
cookie_secure(...)
cookie_http_only(true)
session_lifecycle(PersistentSession...session_ttl...)
safer SESSION_KEY handling (no fixed default secret)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      if valid {
            session.renew();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   if valid {
            session.renew();
            session
                .insert("username", user.username.clone())
                .map_err(error::ErrorInternalServerError)?;
            session
                .insert("user_id", user.id)
                .map_err(error::ErrorInternalServerError)?;
            session
                .insert("role", role.clone())
                .map_err(error::ErrorInternalServerError)?;
            println!("[login] session_set username={}", user.username);
            let response = ApiResponse {
                message: "Login successful".to_string(),
                data: AuthUser {
                    username: user.username,
                    role,
                },
            };
            return Ok(HttpResponse::Ok().json(response));
        }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;On successful login, call session.renew() before inserting session values to reduce session fixation&lt;/strong&gt; &lt;br&gt;
&lt;code&gt;src/handlers/auth.rs&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use actix_session::{
    config::{PersistentSession, TtlExtensionPolicy},
    storage::CookieSessionStore,
    SessionMiddleware,
};
use actix_web::{
    cookie::{time::Duration, Key, SameSite},
    web, App, HttpServer,
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    let session_key = std::env::var("SESSION_KEY").unwrap_or_else(|_| {
        eprintln!("[startup] SESSION_KEY is missing; generating ephemeral key for this process.");
        format!("{}{}", uuid::Uuid::new_v4(), uuid::Uuid::new_v4())
    });
    let mut session_key_bytes = session_key.into_bytes();
    if session_key_bytes.len() &amp;lt; 32 {
        session_key_bytes.resize(32, b'0');
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;App::new()
            .app_data(state.clone())
            .wrap(cors)
            .wrap(
                SessionMiddleware::builder(CookieSessionStore::default(), key.clone())
                    .cookie_name("rust_crud_session".to_string())
                    .cookie_secure(cfg.session_secure_cookie)
                    .cookie_http_only(true)
                    .cookie_same_site(SameSite::Lax)
                    .session_lifecycle(
                        PersistentSession::default()
                            .session_ttl(Duration::hours(cfg.session_ttl_hours))
                            .session_ttl_extension_policy(TtlExtensionPolicy::OnEveryRequest),
                    )
                    .build(),
            )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;full code&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mod config;
mod db;
mod handlers;
mod layout;
mod middleware;
mod models;

use actix_cors::Cors;
use actix_files::Files;
use actix_session::{
    config::{PersistentSession, TtlExtensionPolicy},
    storage::CookieSessionStore,
    SessionMiddleware,
};
use actix_web::{
    cookie::{time::Duration, Key, SameSite},
    web, App, HttpServer,
};
use config::AppConfig;
use db::{init_pool, normalize_brand_model_rows, normalize_shop_rows, state_data, AppState};
use dotenvy::dotenv;

#[actix_web::main]
async fn main() -&amp;gt; std::io::Result&amp;lt;()&amp;gt; {
    dotenv().ok();
    std::fs::create_dir_all("uploads/brand_models")?;
    std::fs::create_dir_all("uploads/insurance")?;
    std::fs::create_dir_all("uploads/pollution")?;
    std::fs::create_dir_all("uploads/rc_document")?;
    let cfg = AppConfig::from_env();
    let pool = init_pool(&amp;amp;cfg.database_url)
        .await
        .expect("Database connection failed");
    if let Err(err) = normalize_brand_model_rows(&amp;amp;pool).await {
        eprintln!("[startup] normalize_brand_model_rows failed: {err}");
    }
    if let Err(err) = normalize_shop_rows(&amp;amp;pool).await {
        eprintln!("[startup] normalize_shop_rows failed: {err}");
    }

    let state = state_data(AppState {
        pool,
        app_name: cfg.app_name.clone(),
    });

    let session_key = std::env::var("SESSION_KEY").unwrap_or_else(|_| {
        eprintln!("[startup] SESSION_KEY is missing; generating ephemeral key for this process.");
        format!("{}{}", uuid::Uuid::new_v4(), uuid::Uuid::new_v4())
    });
    let mut session_key_bytes = session_key.into_bytes();
    if session_key_bytes.len() &amp;lt; 32 {
        session_key_bytes.resize(32, b'0');
    }
    let key = Key::derive_from(&amp;amp;session_key_bytes);

    HttpServer::new(move || {
        let cors = Cors::default()
            .allowed_origin("http://localhost:5173")
            .allowed_origin("http://127.0.0.1:5173")
            .allowed_origin("http://localhost:5174")
            .allowed_origin("http://127.0.0.1:5174")
            .allowed_origin("http://localhost:8080")
            .allowed_origin("http://127.0.0.1:8080")
            .allowed_origin("http://localhost:8081")
            .allowed_origin("http://127.0.0.1:8081")
            .allow_any_header()
            .allow_any_method()
            .supports_credentials();

        App::new()
            .app_data(state.clone())
            .wrap(cors)
            .wrap(
                SessionMiddleware::builder(CookieSessionStore::default(), key.clone())
                    .cookie_name("rust_crud_session".to_string())
                    .cookie_secure(cfg.session_secure_cookie)
                    .cookie_http_only(true)
                    .cookie_same_site(SameSite::Lax)
                    .session_lifecycle(
                        PersistentSession::default()
                            .session_ttl(Duration::hours(cfg.session_ttl_hours))
                            .session_ttl_extension_policy(TtlExtensionPolicy::OnEveryRequest),
                    )
                    .build(),
            )
            .service(
                web::scope("/api")
                    .route("/login", web::post().to(handlers::login))
                    .route("/logout", web::post().to(handlers::logout))
                    .route("/home/vehicles", web::get().to(handlers::list_home_vehicle_cards_handler))
                    .service(
                        web::scope("")
                            .wrap(middleware::AuthMiddleware)
                            .route("/me", web::get().to(handlers::me))
                            .route("/dashboard", web::get().to(handlers::dashboard))
                            .service(
                                web::scope("")
                                    .wrap(middleware::require_roles(&amp;amp;["user"]))
                                    .route("/shops", web::get().to(handlers::list_shops_handler))
                                    .route("/shops", web::post().to(handlers::create_shop_handler))
                                    .route("/shops/{id}", web::get().to(handlers::get_shop_handler))
                                    .route("/shops/{id}", web::put().to(handlers::update_shop_handler))
                                    .route("/shops/{id}", web::delete().to(handlers::delete_shop_handler))
                                    .route("/vehicles", web::get().to(handlers::list_vehicles_handler))
                                    .route("/vehicles", web::post().to(handlers::create_vehicle_handler))
                                    .route(
                                        "/vehicles/upload-documents",
                                        web::post().to(handlers::upload_vehicle_documents_handler),
                                    )
                                    .route(
                                        "/vehicles/upload-partner-image",
                                        web::post().to(handlers::upload_vehicle_partner_image_handler),
                                    )
                                    .route("/vehicles/{id}", web::get().to(handlers::get_vehicle_handler))
                                    .route("/vehicles/{id}", web::put().to(handlers::update_vehicle_handler))
                                    .route("/vehicles/{id}", web::delete().to(handlers::delete_vehicle_handler))
                                    .route("/bookings/offline", web::post().to(handlers::save_offline_booking_handler))
                                    .route("/brand-models", web::get().to(handlers::list_brand_models_handler))
                                    .route("/brand-models", web::post().to(handlers::create_brand_model_handler))
                                    .route(
                                        "/brand-models/upload-images",
                                        web::post().to(handlers::upload_brand_model_images_handler),
                                    )
                                    .route(
                                        "/brand-models/upload-images/",
                                        web::post().to(handlers::upload_brand_model_images_handler),
                                    )
                                    .route(
                                        "/brand-model/upload-images",
                                        web::post().to(handlers::upload_brand_model_images_handler),
                                    )
                                    .route("/brand-models/{id}", web::get().to(handlers::get_brand_model_handler))
                                    .route("/brand-models/{id}", web::put().to(handlers::update_brand_model_handler))
                                    .route("/brand-models/{id}", web::delete().to(handlers::delete_brand_model_handler)),
                            ),
                    ),
            )
            .service(Files::new("/uploads", "./uploads"))
    })
    .bind(cfg.bind_addr)?
    .run()
    .await
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Explanation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  let session_ttl_hours = env::var("SESSION_TTL_HOURS")
            .ok()
            .and_then(|v| v.parse::&amp;lt;i64&amp;gt;().ok())
            .filter(|v| *v &amp;gt; 0)
            .unwrap_or(24);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://www.debug.school/images/x9L0DAOTAJFOwYw_rnklOidt-5iiOu2IKAfbQ_2eqS0/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvcW5xeTMw/bm10YjBhNDBqZHg5/OTAucG5n" class="article-body-image-wrapper"&gt;&lt;img src="https://www.debug.school/images/x9L0DAOTAJFOwYw_rnklOidt-5iiOu2IKAfbQ_2eqS0/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvcW5xeTMw/bm10YjBhNDBqZHg5/OTAucG5n" alt=" " width="462" height="702"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;alternative way&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Same Logic in Beginner Style (Long Version)&lt;/p&gt;

&lt;p&gt;This is the same code written in a more beginner friendly style.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use std::env;

fn main() {

    let value = env::var("SESSION_TTL_HOURS");

    let session_ttl_hours = match value {

        Ok(v) =&amp;gt; {
            match v.parse::&amp;lt;i64&amp;gt;() {
                Ok(num) if num &amp;gt; 0 =&amp;gt; num,
                _ =&amp;gt; 24
            }
        }

        Err(_) =&amp;gt; 24
    };

    println!("Session TTL = {}", session_ttl_hours);

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Output is the same.&lt;/code&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Understanding the Two-Layer Architecture of Actix Middleware: Transform vs Service</title>
      <dc:creator>rakesh kumar</dc:creator>
      <pubDate>Fri, 06 Mar 2026 02:57:33 +0000</pubDate>
      <link>https://www.debug.school/rakeshdevcotocus_468/understanding-the-two-layer-architecture-of-actix-middleware-transform-vs-service-3go2</link>
      <guid>https://www.debug.school/rakeshdevcotocus_468/understanding-the-two-layer-architecture-of-actix-middleware-transform-vs-service-3go2</guid>
      <description>&lt;p&gt;&lt;strong&gt;Why do we need both Transform and Service?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Why Actix Middleware Has Two Layers&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Simple Real-World Analogy&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;What Transform Does&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;What Service Does&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Core Difference&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Visual Flow&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Now Actual Actix Middleware Example&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Step-by-Step Theory of the Code&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Simple Understanding of Left and Right Body&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;What Happens at Runtime&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Objective and MCQ&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When developers start building custom middleware in Actix-Web, one concept creates the most confusion:&lt;/p&gt;
&lt;h2&gt;
  
  
  Why do we need both Transform and Service?
&lt;/h2&gt;

&lt;p&gt;At first, it feels like both are doing the same job. But in reality, they have different responsibilities.&lt;/p&gt;

&lt;p&gt;This is the core idea:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Transform&lt;/code&gt; creates the middleware&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Service&lt;/code&gt; runs the middleware logic for each request&lt;/p&gt;

&lt;p&gt;Once you understand this two-layer architecture, custom middleware becomes much easier.&lt;/p&gt;
&lt;h2&gt;
  
  
  Why Actix Middleware Has Two Layers
&lt;/h2&gt;

&lt;p&gt;Actix middleware is designed in a flexible and reusable way.&lt;/p&gt;

&lt;p&gt;A middleware must do two separate things:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Layer 1: Build the middleware&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This happens when Actix sets up your app.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Layer 2: Process every incoming request&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This happens every time a user calls an API route.&lt;/p&gt;

&lt;p&gt;Because these are two different jobs, Actix separates them into:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Transform

Service
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Simple Real-World Analogy
&lt;/h2&gt;

&lt;p&gt;Think of a security system in an office.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Transform&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;This is the company that installs the security gate.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Service&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;This is the security guard who checks every person entering.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;the gate is created once

the checking happens again and again for each visitor
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That is exactly how middleware works in Actix.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  What Transform Does
&lt;/h2&gt;

&lt;p&gt;Transform is the middleware factory.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Its job is:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
receive the next inner service

wrap it

return a new middleware service
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;In simple words:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Transform prepares the middleware structure.&lt;/p&gt;

&lt;p&gt;It does not handle every request directly.&lt;/p&gt;

&lt;p&gt;Basic Theory of Transform&lt;/p&gt;

&lt;p&gt;When you use:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
.wrap(AuthMiddleware)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Actix calls Transform behind the scenes.&lt;/p&gt;

&lt;p&gt;It says:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;“Here is the inner service. Build a middleware around it.”
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So Transform is like a constructor or factory.&lt;/p&gt;

&lt;p&gt;2.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Service Does
&lt;/h2&gt;

&lt;p&gt;Service is the real request processor.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Its job is:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;receive each request

inspect it

decide whether to block or allow

call the next service if allowed
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;In simple words:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Service contains the actual middleware logic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;This is where you write code like:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;check session

check token

check role

log request
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;measure response time&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Core Difference
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Transform&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;runs when middleware is attached

creates the middleware wrapper

setup layer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Service&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;runs on every request

executes middleware logic

runtime layer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Visual Flow
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;App Startup
   ↓
Transform runs
   ↓
Middleware service created
   ↓
-----------------------------
Each Client Request
   ↓
Service runs
   ↓
Check request
   ↓
Allow or block
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;A Very Simple Rust Example First&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Before Actix, let us understand the idea using plain Rust thinking.&lt;/p&gt;

&lt;p&gt;Factory example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct GateFactory;

struct Gate;

impl GateFactory {
    fn build(&amp;amp;self) -&amp;gt; Gate {
        Gate
    }
}

impl Gate {
    fn check(&amp;amp;self, name: &amp;amp;str) {
        println!("Checking entry for {}", name);
    }
}

fn main() {
    let factory = GateFactory;
    let gate = factory.build();

    gate.check("Ashwani");
    gate.check("Ravi");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Checking entry for Ashwani
Checking entry for Ravi
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Explanation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;GateFactory = like Transform

Gate = like Service
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Factory creates the gate once.&lt;br&gt;
Gate checks people many times.&lt;/p&gt;

&lt;p&gt;That is the same idea as Actix middleware.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
  
  
  Now Actual Actix Middleware Example
&lt;/h2&gt;

&lt;p&gt;Below is a basic custom authentication middleware.&lt;/p&gt;

&lt;p&gt;It checks whether request contains header x-auth-token.&lt;/p&gt;

&lt;p&gt;If header is missing:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return 401 Unauthorized
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If present:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;allow request to continue
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Full Middleware Code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use std::future::{ready, Ready};
use std::rc::Rc;

use actix_web::{
    body::{EitherBody, MessageBody},
    dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
    Error, HttpResponse,
};
use futures_util::future::LocalBoxFuture;

pub struct AuthMiddleware;

impl&amp;lt;S, B&amp;gt; Transform&amp;lt;S, ServiceRequest&amp;gt; for AuthMiddleware
where
    S: Service&amp;lt;ServiceRequest, Response = ServiceResponse&amp;lt;B&amp;gt;, Error = Error&amp;gt; + 'static,
    B: MessageBody + 'static,
{
    type Response = ServiceResponse&amp;lt;EitherBody&amp;lt;B&amp;gt;&amp;gt;;
    type Error = Error;
    type InitError = ();
    type Transform = AuthMiddlewareService&amp;lt;S&amp;gt;;
    type Future = Ready&amp;lt;Result&amp;lt;Self::Transform, Self::InitError&amp;gt;&amp;gt;;

    fn new_transform(&amp;amp;self, service: S) -&amp;gt; Self::Future {
        ready(Ok(AuthMiddlewareService {
            service: Rc::new(service),
        }))
    }
}

pub struct AuthMiddlewareService&amp;lt;S&amp;gt; {
    service: Rc&amp;lt;S&amp;gt;,
}

impl&amp;lt;S, B&amp;gt; Service&amp;lt;ServiceRequest&amp;gt; for AuthMiddlewareService&amp;lt;S&amp;gt;
where
    S: Service&amp;lt;ServiceRequest, Response = ServiceResponse&amp;lt;B&amp;gt;, Error = Error&amp;gt; + 'static,
    B: MessageBody + 'static,
{
    type Response = ServiceResponse&amp;lt;EitherBody&amp;lt;B&amp;gt;&amp;gt;;
    type Error = Error;
    type Future = LocalBoxFuture&amp;lt;'static, Result&amp;lt;Self::Response, Self::Error&amp;gt;&amp;gt;;

    forward_ready!(service);

    fn call(&amp;amp;self, req: ServiceRequest) -&amp;gt; Self::Future {
        let service = self.service.clone();

        Box::pin(async move {
            let has_token = req.headers().contains_key("x-auth-token");

            if !has_token {
                let response = HttpResponse::Unauthorized().body("Missing auth token");
                return Ok(req.into_response(response).map_into_right_body());
            }

            let response = service.call(req).await?;
            Ok(response.map_into_left_body())
        })
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Step-by-Step Theory of the Code
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Part 1: Middleware marker struct&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pub struct AuthMiddleware;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the middleware type you attach with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.wrap(AuthMiddleware)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This struct does not contain logic itself.&lt;br&gt;
It simply represents the middleware.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Part 2: Transform implementation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;impl&amp;lt;S, B&amp;gt; Transform&amp;lt;S, ServiceRequest&amp;gt; for AuthMiddleware
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This means:&lt;/p&gt;

&lt;p&gt;AuthMiddleware can transform an inner service into a middleware-wrapped service.&lt;/p&gt;

&lt;p&gt;Here:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
S = inner service

B = body type
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Part 3: new_transform()&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn new_transform(&amp;amp;self, service: S) -&amp;gt; Self::Future {
    ready(Ok(AuthMiddlewareService {
        service: Rc::new(service),
    }))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the most important Transform function.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What it does&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;receives the inner service

wraps it inside AuthMiddlewareService

returns it
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So this is the creation layer.&lt;/p&gt;

&lt;p&gt;This happens when Actix builds the middleware pipeline.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Part 4: middleware service struct&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pub struct AuthMiddlewareService&amp;lt;S&amp;gt; {
    service: Rc&amp;lt;S&amp;gt;,
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This struct stores the inner service.&lt;/p&gt;

&lt;p&gt;After middleware check passes, request will be forwarded to this inner service.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Part 5: Service implementation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;impl&amp;lt;S, B&amp;gt; Service&amp;lt;ServiceRequest&amp;gt; for AuthMiddlewareService&amp;lt;S&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This means:&lt;/p&gt;

&lt;p&gt;AuthMiddlewareService behaves like a service that can process requests.&lt;/p&gt;

&lt;p&gt;This is the runtime layer.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Part 6: call() method&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn call(&amp;amp;self, req: ServiceRequest) -&amp;gt; Self::Future
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This method runs on every request.&lt;/p&gt;

&lt;p&gt;This is where the actual middleware logic is written.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Part 7: request checking logic&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let has_token = req.headers().contains_key("x-auth-token");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Middleware checks whether request has authentication token.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Part 8: block unauthorized request&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if !has_token {
    let response = HttpResponse::Unauthorized().body("Missing auth token");
    return Ok(req.into_response(response).map_into_right_body());
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;If token missing:&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;middleware stops request&lt;/p&gt;

&lt;p&gt;returns 401 Unauthorized&lt;/p&gt;

&lt;p&gt;This is middleware-generated response.&lt;/p&gt;

&lt;p&gt;So it uses:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;map_into_right_body()
Part 9: allow request to continue
let response = service.call(req).await?;
Ok(response.map_into_left_body())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;If token exists:&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;middleware forwards request to inner service&lt;/p&gt;

&lt;p&gt;handler runs normally&lt;/p&gt;

&lt;p&gt;This is handler-generated response.&lt;/p&gt;

&lt;p&gt;So it uses:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;map_into_left_body()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Simple Understanding of Left and Right Body
&lt;/h2&gt;

&lt;p&gt;In middleware there can be two response sources:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Left body&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Normal handler response
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Right body&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Middleware custom response&lt;/p&gt;

&lt;p&gt;So remember:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;map_into_left_body() = request allowed

map_into_right_body() = request blocked by middleware
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;How to Use This Middleware in main.rs&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use actix_web::{web, App, HttpResponse, HttpServer, Responder};

mod auth_middleware;
use auth_middleware::AuthMiddleware;

async fn dashboard() -&amp;gt; impl Responder {
    HttpResponse::Ok().body("Welcome to dashboard")
}

#[actix_web::main]
async fn main() -&amp;gt; std::io::Result&amp;lt;()&amp;gt; {
    HttpServer::new(|| {
        App::new()
            .service(
                web::scope("/api")
                    .wrap(AuthMiddleware)
                    .route("/dashboard", web::get().to(dashboard))
            )
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  What Happens at Runtime
&lt;/h2&gt;

&lt;p&gt;App startup&lt;/p&gt;

&lt;p&gt;When application starts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.wrap(AuthMiddleware)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Actix triggers Transform.&lt;/p&gt;

&lt;p&gt;So:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Transform creates AuthMiddlewareService
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;middleware pipeline is prepared&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Request 1: No token&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;User sends request without header:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;GET /api/dashboard
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Middleware Service runs:&lt;/p&gt;

&lt;p&gt;checks header&lt;/p&gt;

&lt;p&gt;header missing&lt;/p&gt;

&lt;p&gt;returns 401&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Output&lt;/code&gt;&lt;br&gt;
Missing auth token&lt;br&gt;
&lt;strong&gt;Request 2: With token&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;User sends request with header:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x-auth-token: abc123
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Middleware Service runs:&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;checks header

token exists

forwards request to handler

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Handler returns:&lt;/p&gt;

&lt;p&gt;Welcome to dashboard&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Output Summary&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Without token
Status: 401 Unauthorized
Body: Missing auth token
With token
Status: 200 OK
Body: Welcome to dashboard
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Why Beginners Get Confused&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Many beginners think middleware is only one thing.&lt;/p&gt;

&lt;p&gt;They expect:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;one struct

one trait

one request handler
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But Actix separates middleware into two levels:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Level 1: Creation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Handled by Transform
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Level 2: Execution&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Handled by Service
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This design gives Actix great flexibility.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Interview-Style Answer&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If someone asks in interview:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;What is the difference between Transform and Service in Actix middleware?
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can answer like this:&lt;/p&gt;

&lt;p&gt;In Actix custom middleware, Transform acts as a factory that creates the middleware wrapper around the inner service. It runs when the application pipeline is built. Service contains the actual middleware logic and runs on every incoming request. Transform is the setup layer, while Service is the execution layer.&lt;/p&gt;

&lt;h2&gt;
  
  
  Objective and MCQ
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;What is the main purpose of middleware in Actix-web?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. Handle database queries&lt;br&gt;
B. Intercept requests before they reach handlers&lt;br&gt;
C. Compile Rust code faster&lt;br&gt;
D. Replace HTTP responses&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Middleware can inspect or reject requests before they reach handlers.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Middleware in Actix-web is typically implemented using which two traits&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Future and Async&lt;br&gt;
B. Transform and Service&lt;br&gt;
C. Handler and Request&lt;br&gt;
D. Router and Scope&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Middleware is created using Transform (factory) and Service (execution) traits.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which Actix type represents an incoming HTTP request inside middleware?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. HttpRequest&lt;br&gt;
B. ServiceRequest&lt;br&gt;
C. RequestContext&lt;br&gt;
D. RequestBody&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
ServiceRequest contains the request data processed by middleware.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which type represents the response returned from middleware or handlers?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. HttpResponse&lt;br&gt;
B. ServiceResponse&lt;br&gt;
C. ResponseBody&lt;br&gt;
D. HandlerResponse&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
ServiceResponse wraps both request and response objects.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What happens if middleware decides to block a request?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Request continues to handler&lt;br&gt;
B. Middleware returns its own HTTP response&lt;br&gt;
C. Server restarts&lt;br&gt;
D. Request is ignored&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Middleware can stop processing and return an early response.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which HTTP response is commonly returned when authentication fails?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. 200 OK&lt;br&gt;
B. 401 Unauthorized&lt;br&gt;
C. 201 Created&lt;br&gt;
D. 302 Redirect&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which method in middleware processes each incoming request?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. execute()&lt;br&gt;
B. handle()&lt;br&gt;
C. call()&lt;br&gt;
D. run()&lt;/p&gt;

&lt;p&gt;✅ Answer: C&lt;br&gt;
The call() function is where request processing occurs.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;What does forward_ready! macro do in middleware&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Sends response to client&lt;br&gt;
B. Forwards readiness check to inner service&lt;br&gt;
C. Creates a request object&lt;br&gt;
D. Serializes JSON&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Why does middleware often use generics like ?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. To support different services and response body types&lt;br&gt;
B. To reduce code size&lt;br&gt;
C. To store database values&lt;br&gt;
D. To handle logging&lt;/p&gt;

&lt;p&gt;✅ Answer: A&lt;br&gt;
Generics allow middleware to work with any service and body type.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What does S usually represent in middleware generic parameters?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Session object&lt;br&gt;
B. Inner service being wrapped&lt;br&gt;
C. Server configuration&lt;br&gt;
D. Security token&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which trait must response body type implement in Actix middleware?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Clone&lt;br&gt;
B. Serialize&lt;br&gt;
C. MessageBody&lt;br&gt;
D. Future&lt;/p&gt;

&lt;p&gt;✅ Answer: C&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What does the middleware authentication function typically check?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Database schema&lt;br&gt;
B. Request headers or session tokens&lt;br&gt;
C. Compiler version&lt;br&gt;
D. JSON parsing&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What architectural pattern describes middleware execution order?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. MVC pattern&lt;br&gt;
B. Onion / pipeline pattern&lt;br&gt;
C. Observer pattern&lt;br&gt;
D. Singleton pattern&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Middleware layers wrap around handlers like an onion structure.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;In route protection middleware, what usually happens when the user is authenticated?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Request stops&lt;br&gt;
B. Middleware calls the inner service&lt;br&gt;
C. Server logs out user&lt;br&gt;
D. Database connection closes&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Which Actix function allows attaching middleware to an application&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. attach()&lt;br&gt;
B. wrap()&lt;br&gt;
C. register()&lt;br&gt;
D. bind()&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
App::wrap() attaches middleware.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which type is commonly used to represent asynchronous middleware results?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Result&lt;br&gt;
B. LocalBoxFuture&lt;br&gt;
C. AsyncResponse&lt;br&gt;
D. FutureResult&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What is the role of Transform trait in middleware?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Handle request execution&lt;br&gt;
B. Create middleware service instances&lt;br&gt;
C. Manage database connections&lt;br&gt;
D. Serialize responses&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which scenario is a common use case for route protection middleware?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Image processing&lt;br&gt;
B. Authentication and authorization&lt;br&gt;
C. File compression&lt;br&gt;
D. Code compilation&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which middleware logic is typically executed before the handler?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Response serialization&lt;br&gt;
B. Authentication check&lt;br&gt;
C. Database backup&lt;br&gt;
D. File upload&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What is the main advantage of middleware-based route protection?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Reduces database size&lt;br&gt;
B. Centralizes authentication logic&lt;br&gt;
C. Removes need for handlers&lt;br&gt;
D. Increases CPU usage&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Middleware centralizes authentication and security checks for multiple routes.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Understanding Generic Structs in Rust</title>
      <dc:creator>rakesh kumar</dc:creator>
      <pubDate>Fri, 06 Mar 2026 00:42:36 +0000</pubDate>
      <link>https://www.debug.school/rakeshdevcotocus_468/understanding-generic-structs-in-rust-f1</link>
      <guid>https://www.debug.school/rakeshdevcotocus_468/understanding-generic-structs-in-rust-f1</guid>
      <description>&lt;p&gt;For example, you may want a Box-like struct that can store:&lt;br&gt;
&lt;strong&gt;What Are Generics in Simple Words?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Why Generic Structs Are Useful&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Basic Problem Without Generics&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;The Solution: Generic Struct&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Real-Life Use Case of Generic Structs&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Why middleware needs generics&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Objective and MCQ&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;an integer (i32)

a string (String)

a float (f64)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or even a custom struct&lt;/p&gt;

&lt;p&gt;If you don’t use generics, you end up writing separate structs for each type, which is repetitive and hard to maintain.&lt;/p&gt;

&lt;p&gt;That’s exactly why generics exist in Rust.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Are Generics in Simple Words?
&lt;/h2&gt;

&lt;p&gt;A generic type is like a placeholder.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Instead of saying:&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;“This struct only stores i32”
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;You say:&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;“This struct can store any type”
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And Rust will decide the type when you create the struct.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Generic Structs Are Useful&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Generic structs help you:
Avoid duplicate code
Make reusable data structures
Write clean and scalable programs
Keep your code type-safe (Rust still checks types strictly)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Basic Problem Without Generics&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s say you want a struct to store a value.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Example 1: Struct for only i32&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct IntBox {
    value: i32,
}

fn main() {
    let a = IntBox { value: 10 };
    println!("IntBox value = {}", a.value);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;✅ &lt;code&gt;Output&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;IntBox value = 10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now if you want to store a string, you must create a new struct:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Example 2: Struct for only String&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct StringBox {
    value: String,
}

fn main() {
    let b = StringBox { value: "Hello".to_string() };
    println!("StringBox value = {}", b.value);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;✅ &lt;code&gt;Output&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;StringBox value = Hello
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;See the problem?&lt;/p&gt;

&lt;p&gt;You are writing two structs doing the same job, just with different types.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Solution: Generic Struct&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now we create one struct that works for all types:&lt;/p&gt;

&lt;p&gt;Generic Struct Syntax&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct BoxValue&amp;lt;T&amp;gt; {
    value: T,
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here:&lt;/p&gt;

&lt;p&gt;T means any type&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;BoxValue&amp;lt;T&amp;gt; becomes:

BoxValue&amp;lt;i32&amp;gt;

BoxValue&amp;lt;String&amp;gt;

BoxValue&amp;lt;f64&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;etc.&lt;/p&gt;

&lt;p&gt;✅ &lt;strong&gt;Coding Example: Generic Struct with Different Types&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct BoxValue&amp;lt;T&amp;gt; {
    value: T,
}

fn main() {
    let a = BoxValue { value: 10 };
    let b = BoxValue { value: "Hello" };
    let c = BoxValue { value: 99.5 };

    println!("a = {}", a.value);
    println!("b = {}", b.value);
    println!("c = {}", c.value);
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;✅ &lt;code&gt;Output&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a = 10
b = Hello
c = 99.5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;What Happened Here?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Rust automatically decides:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a is BoxValue&amp;lt;i32&amp;gt;

b is BoxValue&amp;lt;&amp;amp;str&amp;gt;

c is BoxValue&amp;lt;f64&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One struct, many types.&lt;/p&gt;

&lt;p&gt;Generic Struct with Methods (impl)&lt;/p&gt;

&lt;p&gt;Generic structs become more powerful when we add methods.&lt;/p&gt;

&lt;p&gt;Example: Add a method get()&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct BoxValue&amp;lt;T&amp;gt; {
    value: T,
}

impl&amp;lt;T&amp;gt; BoxValue&amp;lt;T&amp;gt; {
    fn get(&amp;amp;self) -&amp;gt; &amp;amp;T {
        &amp;amp;self.value
    }
}

fn main() {
    let a = BoxValue { value: 10 };
    let b = BoxValue { value: "Rust" };

    println!("a = {}", a.get());
    println!("b = {}", b.get());
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;✅ &lt;code&gt;Output&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a = 10
b = Rust
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Meaning of impl&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;impl means:&lt;/p&gt;

&lt;p&gt;“Implement these methods for BoxValue of any type T”&lt;/p&gt;

&lt;p&gt;So get() works for i32, String, &amp;amp;str, and everything else.&lt;/p&gt;

&lt;p&gt;Generic Struct with Two Types &lt;/p&gt;

&lt;p&gt;Sometimes you want to store two different types in the same struct.&lt;/p&gt;

&lt;p&gt;Example: store a pair.&lt;/p&gt;

&lt;p&gt;Coding Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct Pair&amp;lt;T, U&amp;gt; {
    first: T,
    second: U,
}

fn main() {
    let p1 = Pair { first: 10, second: "Hello" };
    let p2 = Pair { first: "Name", second: 99.9 };

    println!("p1 = {} {}", p1.first, p1.second);
    println!("p2 = {} {}", p2.first, p2.second);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;✅ &lt;code&gt;Output&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;p1 = 10 Hello
p2 = Name 99.9
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;p1 is Pair&amp;lt;i32, &amp;amp;str&amp;gt;

p2 is Pair&amp;lt;&amp;amp;str, f64&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Real-Life Use Case of Generic Structs&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Generic structs are used everywhere in Rust, such as:&lt;/p&gt;

&lt;p&gt;Vec → vector of any type&lt;/p&gt;

&lt;p&gt;Option → optional value of any type&lt;/p&gt;

&lt;p&gt;Result → success type and error type&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let nums: Vec&amp;lt;i32&amp;gt; = vec![1, 2, 3];
let name: Option&amp;lt;&amp;amp;str&amp;gt; = Some("Ashwani");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;✅ A generic struct uses placeholders like T, U to support many types.&lt;/p&gt;

&lt;p&gt;✅ Instead of writing:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;IntBox

StringBox

FloatBox

You write one struct:

BoxValue&amp;lt;T&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;✅ Generic structs keep code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;reusable

clean

scalable

type-safe
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Why middleware needs generics
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Because different handlers are different types&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In Actix, each handler/service is not the same Rust type.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async fn dashboard() -&amp;gt; HttpResponse {
    HttpResponse::Ok().body("Dashboard")
}

async fn profile() -&amp;gt; HttpResponse {
    HttpResponse::Ok().body("Profile")
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Even if both return HttpResponse, internally the service pipeline around them may be different.&lt;/p&gt;

&lt;p&gt;If middleware was not generic, you would have to write middleware for one exact service type only.&lt;/p&gt;

&lt;p&gt;Generics solve that.&lt;/p&gt;

&lt;p&gt;So:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;AuthMiddlewareService&amp;lt;S&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;means:&lt;/p&gt;

&lt;p&gt;wrap any service type S&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Because response body types can be different&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Different routes may return different body types:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;plain text

JSON

HTML

file response

custom responder body
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So middleware cannot assume only one body type.&lt;/p&gt;

&lt;p&gt;That is why you use:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;B: MessageBody
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This means:&lt;/p&gt;

&lt;p&gt;whatever body type the inner service returns, it must be a valid Actix body&lt;/p&gt;

&lt;p&gt;So B keeps the middleware flexible.&lt;/p&gt;

&lt;h2&gt;
  
  
  Objective and MCQ
&lt;/h2&gt;

&lt;p&gt;1) &lt;strong&gt;Why does middleware in Actix commonly use generics like AuthMiddlewareService?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. To avoid using async/await&lt;br&gt;
B. Because different handlers/services are different Rust types&lt;br&gt;
C. Because Rust does not support traits&lt;br&gt;
D. To make code slower but safer&lt;br&gt;
✅ Answer: B&lt;/p&gt;

&lt;p&gt;2) &lt;strong&gt;In struct BoxValue { value: T }, what does T represent?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. A fixed integer type&lt;br&gt;
B. A placeholder for “any type” chosen at compile time&lt;br&gt;
C. A runtime dynamic type&lt;br&gt;
D. A pointer type&lt;br&gt;
✅ Answer: B&lt;/p&gt;

&lt;p&gt;3) &lt;strong&gt;Without generics, storing i32 and String typically leads to&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;A. One struct that auto-converts types&lt;br&gt;
B. Duplicate structs for each type (repetition)&lt;br&gt;
C. Faster compilation only&lt;br&gt;
D. Trait objects everywhere&lt;br&gt;
✅ Answer: B&lt;/p&gt;

&lt;p&gt;4) &lt;strong&gt;Which is the correct generic struct syntax?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. struct BoxValue(value: T)&lt;br&gt;
B. struct BoxValue { value: T }&lt;br&gt;
C. struct BoxValue[T] { value: T }&lt;br&gt;
D. struct BoxValue { value:  }&lt;br&gt;
✅ Answer: B&lt;/p&gt;

&lt;p&gt;5) &lt;strong&gt;What does impl BoxValue mean?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. Implement methods only for BoxValue&lt;br&gt;
B. Implement methods for BoxValue of any type T&lt;br&gt;
C. Implement methods at runtime depending on input&lt;br&gt;
D. Implement methods only for String&lt;br&gt;
✅ Answer: B&lt;/p&gt;

&lt;p&gt;6) &lt;strong&gt;In a generic method fn get(&amp;amp;self) -&amp;gt; &amp;amp;T, what is returned&lt;/strong&gt;?&lt;/p&gt;

&lt;p&gt;A. A copy of T always&lt;br&gt;
B. A reference to the stored value&lt;br&gt;
C. A mutable reference always&lt;br&gt;
D. A string representation&lt;br&gt;
✅ Answer: B&lt;/p&gt;

&lt;p&gt;7) &lt;strong&gt;Which generic struct supports storing two different types?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. struct Pair { first: T, second: U }&lt;br&gt;
B. struct Pair { first: T, second: T }&lt;br&gt;
C. struct Pair { first: T, second: U }&lt;br&gt;
D. struct Pair { ... }&lt;br&gt;
✅ Answer: A&lt;/p&gt;

&lt;p&gt;8) &lt;strong&gt;If p1 = Pair { first: 10, second: "Hello" }, then p1 is:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. Pair&lt;br&gt;
B. Pair&lt;br&gt;
C. Pair&lt;br&gt;
D. Pair&amp;lt;&amp;amp;str, &amp;amp;str&amp;gt;&lt;br&gt;
✅ Answer: B&lt;/p&gt;

&lt;p&gt;9) &lt;strong&gt;In Actix middleware, why is the response body often generic as B?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. Because every route returns the same body type&lt;br&gt;
B. Because different routes can return different body types (text/JSON/HTML/etc.)&lt;br&gt;
C. Because HttpResponse can’t carry bodies&lt;br&gt;
D. Because generics are required in every Rust file&lt;br&gt;
✅ Answer: B&lt;/p&gt;

&lt;p&gt;10) &lt;strong&gt;Which constraint ensures the body type is valid for Actix?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. B: Clone&lt;br&gt;
B. B: Default&lt;br&gt;
C. B: MessageBody&lt;br&gt;
D. B: Send + Sync&lt;br&gt;
✅ Answer: C&lt;/p&gt;

&lt;p&gt;11) &lt;strong&gt;In AuthMiddlewareService, what does S usually represent?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. A String&lt;br&gt;
B. The wrapped inner service/handler pipeline type&lt;br&gt;
C. A Session&lt;br&gt;
D. A Server config object&lt;br&gt;
✅ Answer: B&lt;/p&gt;

&lt;p&gt;12)&lt;strong&gt;Which statement best describes why generics keep middleware reusable?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. It makes middleware work only for one route&lt;br&gt;
B. It lets middleware wrap “any service type S” instead of one fixed type&lt;br&gt;
C. It removes the need for HTTP responses&lt;br&gt;
D. It converts Rust into a dynamic language&lt;br&gt;
✅ Answer: B&lt;/p&gt;

&lt;p&gt;13) &lt;strong&gt;Which of these is a real-life generic type example mentioned in the topic?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. Vec&lt;br&gt;
B. Tree (as a built-in)&lt;br&gt;
C. Json (as Rust standard library)&lt;br&gt;
D. Router (as standard)&lt;br&gt;
✅ Answer: A&lt;/p&gt;

&lt;p&gt;14) &lt;strong&gt;Option&amp;lt;&amp;amp;str&amp;gt; is an example of:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. A non-generic type&lt;br&gt;
B. A generic type instantiated with &amp;amp;str&lt;br&gt;
C. A macro expansion only&lt;br&gt;
D. A runtime reflection type&lt;br&gt;
✅ Answer: B&lt;/p&gt;

&lt;p&gt;15) &lt;strong&gt;Which is TRUE about generics in Rust?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. Rust decides T only at runtime&lt;br&gt;
B. Generics reduce type safety&lt;br&gt;
C. Generics help reuse code while staying type-safe&lt;br&gt;
D. Generics require garbage collection&lt;br&gt;
✅ Answer: C&lt;/p&gt;

&lt;p&gt;16) &lt;strong&gt;If middleware returns unauthorized early, but otherwise passes through the inner service, why might Actix use an “either body” approach?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. Because both branches must have the same exact body type&lt;br&gt;
B. Because unauthorized and normal responses may have different body types, so they’re unified into one response body type&lt;br&gt;
C. Because Rust cannot return a response&lt;br&gt;
D. Because cookies require it&lt;br&gt;
✅ Answer: B (matches the “different body types” idea behind B: MessageBody)&lt;/p&gt;

&lt;p&gt;17) &lt;strong&gt;In generic structs, what is the main benefit compared to writing IntBox, StringBox, FloatBox separately?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. More duplication&lt;br&gt;
B. One reusable struct for many types&lt;br&gt;
C. Only works for numbers&lt;br&gt;
D. Only works for strings&lt;br&gt;
✅ Answer: B&lt;/p&gt;

&lt;p&gt;18) &lt;strong&gt;Which of the following is a correct instantiation idea for BoxValue?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. BoxValue stores an i32&lt;br&gt;
B. BoxValue stores a String&lt;br&gt;
C. BoxValue stores an i32&lt;br&gt;
D. BoxValue stores a bool only&lt;br&gt;
✅ Answer: A&lt;/p&gt;

&lt;p&gt;19) &lt;strong&gt;In Actix, even if two handlers both “return HttpResponse”, why can their internal service pipeline types differ?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. Because Rust randomly changes types&lt;br&gt;
B. Because different routes/middleware stacks can create different composed service types&lt;br&gt;
C. Because HttpResponse is generic&lt;br&gt;
D. Because handlers cannot be async&lt;br&gt;
✅ Answer: B&lt;/p&gt;

&lt;p&gt;20) &lt;strong&gt;Best summary: “Why middleware needs generics” includes which TWO main reasons?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. (1) Generics make code longer, (2) generics avoid traits&lt;br&gt;
B. (1) Different handlers/services are different types, (2) response body types can differ&lt;br&gt;
C. (1) Generics remove async, (2) generics remove JSON&lt;br&gt;
D. (1) Generics are only for performance, (2) generics are only for macros&lt;br&gt;
✅ Answer: B&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Understanding Different Types of Service Responses in Rust</title>
      <dc:creator>rakesh kumar</dc:creator>
      <pubDate>Fri, 06 Mar 2026 00:21:22 +0000</pubDate>
      <link>https://www.debug.school/rakeshdevcotocus_468/understanding-different-types-of-service-responses-in-rust-1oi3</link>
      <guid>https://www.debug.school/rakeshdevcotocus_468/understanding-different-types-of-service-responses-in-rust-1oi3</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;What Is a Service Response in Rust?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Types of Service Responses in Rust&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Result Response&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Option Response&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Structured API Response&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;HTTP Service Response&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Middleware Service Response&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Generic Service Response&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;EitherBody Response&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Objective and MCQ&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When building backend services in Rust—especially with web frameworks like Actix-Web or similar service architectures—handling responses properly is crucial. A service response represents the output returned after a request is processed by a handler, middleware, or service layer.&lt;/p&gt;

&lt;p&gt;Rust encourages explicit and type-safe response handling. Instead of loosely structured outputs, Rust relies on clear types and structures to represent successful results, errors, optional values, or HTTP responses. This approach improves reliability, readability, and maintainability in server applications.&lt;/p&gt;

&lt;p&gt;In this blog, we will explore the different types of service responses in Rust, understand the theory behind them, and examine their syntax with simple coding examples.&lt;/p&gt;
&lt;h2&gt;
  
  
  What Is a Service Response in Rust?
&lt;/h2&gt;

&lt;p&gt;A service response is the result returned by a function or service after processing input. It could represent:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Successful execution

Failure or error

Optional data

HTTP response for APIs

Structured response objects
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In Rust-based services, responses are usually expressed through types, ensuring safe and predictable program behavior.&lt;/p&gt;

&lt;h2&gt;
  
  
  Types of Service Responses in Rust
&lt;/h2&gt;

&lt;p&gt;Common response types used in Rust services include:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Result Response

Option Response

Structured API Response

HTTP Service Response

Middleware Service Response

Generic Service Response
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's explore each type.&lt;/p&gt;

&lt;h2&gt;
  
  
  Result Response
&lt;/h2&gt;

&lt;p&gt;The Result type is used when a service operation may succeed or fail.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Theory&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Rust avoids exceptions. Instead, functions return Result to represent two possibilities:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
Ok(T) → operation successful

Err(E) → operation failed
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Syntax&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Result&amp;lt;T, E&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Where:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;T = success type

E = error type
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn fetch_user(id: i32) -&amp;gt; Result&amp;lt;String, String&amp;gt; {

    if id == 1 {
        Ok("User Found".to_string())
    } else {
        Err("User Not Found".to_string())
    }

}

fn main() {

    let response = fetch_user(1);

    match response {
        Ok(data) =&amp;gt; println!("Success: {}", data),
        Err(e) =&amp;gt; println!("Error: {}", e),
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Output&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Success: User Found
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Option Response
&lt;/h2&gt;

&lt;p&gt;The Option type represents a value that may or may not exist.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Theory&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Instead of returning null values, Rust uses:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Some(value)

None

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Syntax&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Option&amp;lt;T&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn find_number(num: i32) -&amp;gt; Option&amp;lt;i32&amp;gt; {

    if num == 10 {
        Some(num)
    } else {
        None
    }

}

fn main() {

    match find_number(10) {
        Some(v) =&amp;gt; println!("Found {}", v),
        None =&amp;gt; println!("Value not found"),
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Output&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Found 10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Structured Service Response
&lt;/h2&gt;

&lt;p&gt;Often APIs return structured responses containing metadata.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Theory&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Instead of returning raw values, services return structured response objects containing:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;success status

message

data
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Syntax&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct ApiResponse&amp;lt;T&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct ApiResponse&amp;lt;T&amp;gt; {
    success: bool,
    message: String,
    data: T,
}

fn main() {

    let response = ApiResponse {
        success: true,
        message: "User created".to_string(),
        data: 101,
    };

    println!("Status: {}", response.success);
    println!("Message: {}", response.message);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Output&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Status: true
Message: User created
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  HTTP Service Response
&lt;/h2&gt;

&lt;p&gt;When building web services, responses are returned as HTTP responses.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Theory&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Frameworks like Actix-Web allow creating responses using HTTP status codes and body content.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Syntax&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;HttpResponse::Status().body(data)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use actix_web::HttpResponse;

fn success() -&amp;gt; HttpResponse {

    HttpResponse::Ok().body("Request Successful")

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Output&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;HTTP 200 OK
Request Successful
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Middleware Service Response
&lt;/h2&gt;

&lt;p&gt;Middleware sits between the request and handler. It can modify or generate responses.&lt;/p&gt;

&lt;p&gt;Theory&lt;/p&gt;

&lt;p&gt;In middleware, responses are often wrapped using:&lt;/p&gt;

&lt;p&gt;ServiceResponse&lt;b&gt;&lt;/b&gt;&lt;/p&gt;

&lt;p&gt;This type contains:&lt;/p&gt;

&lt;p&gt;request context&lt;/p&gt;

&lt;p&gt;response body&lt;/p&gt;

&lt;p&gt;status information&lt;/p&gt;

&lt;p&gt;Conceptual Flow&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Request
   ↓
Middleware
   ↓
Handler
   ↓
ServiceResponse
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example Concept&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let response = HttpResponse::Unauthorized().body("Login required");
req.into_response(response);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This creates a ServiceResponse from an HTTP response.&lt;/p&gt;

&lt;h2&gt;
  
  
  Generic Service Response
&lt;/h2&gt;

&lt;p&gt;Rust also supports generic responses that can handle different types of data.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Theory&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Generics allow services to return flexible data types.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Syntax&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct Response&amp;lt;T&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Example&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct Response&amp;lt;T&amp;gt; {
    data: T,
}

fn main() {

    let r1 = Response { data: 10 };
    let r2 = Response { data: "Rust Service" };

    println!("r1: {}", r1.data);
    println!("r2: {}", r2.data);

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Output&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;r1: 10
r2: Rust Service
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  EitherBody Response
&lt;/h2&gt;

&lt;p&gt;EitherBody comes under the Middleware / Service Response Body category in Rust web frameworks like Actix-Web.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Category of EitherBody&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Category&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Middleware Response Body Type
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or more precisely:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Service Response Body Wrapper
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Why EitherBody Exists&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In middleware, two different responses can happen:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Middleware-generated response&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Example: authentication failed
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Handler-generated response&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Example: dashboard data returned by handler
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rust requires one fixed response type, but middleware may return two different responses.&lt;/p&gt;

&lt;p&gt;So Actix provides:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;EitherBody&amp;lt;B&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;to combine both.&lt;/p&gt;

&lt;p&gt;Concept&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;EitherBody
   ├── Left  → handler response
   └── Right → middleware response
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So middleware can safely return either response.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Syntax&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ServiceResponse&amp;lt;EitherBody&amp;lt;B&amp;gt;&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Where:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;B = handler response body type
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example&lt;br&gt;
Middleware Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use actix_web::{
    body::EitherBody,
    dev::{ServiceRequest, ServiceResponse},
    HttpResponse,
};

fn example(req: ServiceRequest) -&amp;gt; ServiceResponse&amp;lt;EitherBody&amp;gt; {

    let authenticated = false;

    if !authenticated {

        let res = HttpResponse::Unauthorized().body("Login required");

        return req.into_response(res).map_into_right_body();
    }

    let res = HttpResponse::Ok().body("Welcome user");

    req.into_response(res).map_into_left_body()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Output Behavior&lt;/code&gt;&lt;br&gt;
&lt;strong&gt;Case 1 — Not logged in&lt;/strong&gt;&lt;br&gt;
Status: 401 Unauthorized&lt;br&gt;
Body: Login required&lt;/p&gt;

&lt;p&gt;This response uses:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;map_into_right_body()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Meaning:&lt;/p&gt;

&lt;p&gt;EitherBody → Right&lt;br&gt;
&lt;strong&gt;Case 2 — Logged in&lt;/strong&gt;&lt;br&gt;
Status: 200 OK&lt;br&gt;
Body: Welcome user&lt;/p&gt;

&lt;p&gt;This response uses:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;map_into_left_body()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Meaning:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;EitherBody → Left
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Where EitherBody Is Mostly Used&lt;/p&gt;

&lt;p&gt;EitherBody is commonly used in:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Actix middleware

Authentication middleware

Rate limiting middleware

Request validation middleware

Error handling middleware

Because middleware may either:

Allow request → call handler
OR
Block request → return response
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;. &lt;strong&gt;What is ServiceResponse in Actix-web?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. Database response&lt;br&gt;
B. HTTP request container&lt;br&gt;
C. Wrapper around request and response&lt;br&gt;
D. Logging structure&lt;/p&gt;

&lt;p&gt;✅ Answer: C&lt;br&gt;
ServiceResponse wraps both the request and the generated HTTP response.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which function returns the HTTP status code from ServiceResponse?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. status()&lt;br&gt;
B. code()&lt;br&gt;
C. response_status()&lt;br&gt;
D. get_status()&lt;/p&gt;

&lt;p&gt;✅ Answer: A&lt;br&gt;
status() returns the HTTP status code of the response.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What does ServiceResponse&lt;b&gt; represent?&lt;/b&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Response with generic body type B&lt;br&gt;
B. Fixed JSON response&lt;br&gt;
C. Static HTML response&lt;br&gt;
D. Database response&lt;/p&gt;

&lt;p&gt;✅ Answer: A&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;What trait must the body type implement in Actix responses&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Clone&lt;br&gt;
B. MessageBody&lt;br&gt;
C. Future&lt;br&gt;
D. Serialize&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;What does EitherBody represent in Actix&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Database results&lt;br&gt;
B. Two possible body types in a response&lt;br&gt;
C. JSON parser&lt;br&gt;
D. Error handler&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
EitherBody allows responses to contain one of two body types.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Why is EitherBody commonly used in middleware&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. To store database records&lt;br&gt;
B. To return either inner service response or middleware response&lt;br&gt;
C. To compress responses&lt;br&gt;
D. To run async tasks&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Middleware often returns either the inner service response or its own error response.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which method converts response body type to BoxBody?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. map_into_boxed_body()&lt;br&gt;
B. box_body()&lt;br&gt;
C. convert_body()&lt;br&gt;
D. wrap_body()&lt;/p&gt;

&lt;p&gt;✅ Answer: A&lt;br&gt;
map_into_boxed_body() converts a body into BoxBody.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Which method converts a response into EitherBody (Left variant)&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. map_into_left_body()&lt;br&gt;
B. map_into_boxed_body()&lt;br&gt;
C. map_left()&lt;br&gt;
D. into_left()&lt;/p&gt;

&lt;p&gt;✅ Answer: A&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which method converts a response into EitherBody (Right variant)?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. map_into_left_body()&lt;br&gt;
B. map_into_right_body()&lt;br&gt;
C. map_into_boxed_body()&lt;br&gt;
D. map_into_service()&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What does map_body() do in ServiceResponse?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Deletes response body&lt;br&gt;
B. Maps body to another type&lt;br&gt;
C. Converts body to JSON&lt;br&gt;
D. Logs body&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
It transforms the response body to another type using a closure.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;What is the default right variant of EitherBody&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. String&lt;br&gt;
B. BoxBody&lt;br&gt;
C. Vec&lt;br&gt;
D. Json&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
The right variant defaults to BoxBody.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Which method returns reference to the original request&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. get_request()&lt;br&gt;
B. request()&lt;br&gt;
C. original_request()&lt;br&gt;
D. req()&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
request() returns reference to the original request.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which function extracts response and request parts?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. split()&lt;br&gt;
B. extract()&lt;br&gt;
C. into_parts()&lt;br&gt;
D. unwrap()&lt;/p&gt;

&lt;p&gt;✅ Answer: C&lt;br&gt;
into_parts() separates request and response components.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which component typically generates the final response?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Database&lt;br&gt;
B. Middleware&lt;br&gt;
C. Handler&lt;br&gt;
D. Logger&lt;/p&gt;

&lt;p&gt;✅ Answer: C&lt;br&gt;
Handlers generate the main HTTP responses.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;In middleware, what happens if authentication fails?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Request continues&lt;br&gt;
B. Middleware returns its own response&lt;br&gt;
C. Database handles it&lt;br&gt;
D. Program stops&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which HTTP response might middleware generate for unauthorized access?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. 200 OK&lt;br&gt;
B. 201 Created&lt;br&gt;
C. 401 Unauthorized&lt;br&gt;
D. 204 No Content&lt;/p&gt;

&lt;p&gt;✅ Answer: C&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What is the purpose of generics in ServiceResponse&lt;b&gt;?&lt;/b&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. To support different body types&lt;br&gt;
B. To store database records&lt;br&gt;
C. To enable logging&lt;br&gt;
D. To enable caching&lt;/p&gt;

&lt;p&gt;✅ Answer: A&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which response body types can Actix support?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. JSON&lt;br&gt;
B. Text&lt;br&gt;
C. HTML&lt;br&gt;
D. All of the above&lt;/p&gt;

&lt;p&gt;✅ Answer: D&lt;/p&gt;

&lt;p&gt;19.** What architecture pattern does Actix middleware follow?**&lt;/p&gt;

&lt;p&gt;A. Pipeline pattern&lt;br&gt;
B. Onion/chain pattern&lt;br&gt;
C. MVC pattern&lt;br&gt;
D. Repository pattern&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Requests pass through middleware layers like an onion structure.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Why do middleware responses often use generics?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. To reduce code size&lt;br&gt;
B. Because body types from inner services are unknown&lt;br&gt;
C. To speed up compilation&lt;br&gt;
D. To simplify syntax&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Middleware must support unknown body types returned by handlers&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Understanding Different Types of Responses in Rust: Theory, Syntax, and Practical Examples</title>
      <dc:creator>rakesh kumar</dc:creator>
      <pubDate>Fri, 06 Mar 2026 00:03:51 +0000</pubDate>
      <link>https://www.debug.school/rakeshdevcotocus_468/understanding-different-types-of-responses-in-rust-theory-syntax-and-practical-examples-4lig</link>
      <guid>https://www.debug.school/rakeshdevcotocus_468/understanding-different-types-of-responses-in-rust-theory-syntax-and-practical-examples-4lig</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;custom structured responses&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Common Response Types in Rust&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Result&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Option&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;HttpResponse (Web APIs)&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;impl Responder&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;ServiceResponse&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Custom struct responses&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;JSON responses&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Objective and MCQ&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;When building backend applications or APIs in Rust, returning the correct response type is very important. A response is the data that the server sends back to the client after processing a request.&lt;/p&gt;

&lt;p&gt;Rust provides several ways to return responses depending on the situation. For example, a function may return:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a success response

an error response

optional data

JSON data
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  custom structured responses
&lt;/h2&gt;

&lt;p&gt;Understanding these response types helps developers build clean, safe, and maintainable Rust applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is a Response in Rust?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A response represents the result of a computation or request. It tells the caller whether the operation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;succeeded

failed

returned data

returned nothing
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rust commonly uses special enums and types to represent responses safely.&lt;/p&gt;

&lt;h2&gt;
  
  
  Common Response Types in Rust
&lt;/h2&gt;

&lt;p&gt;The most commonly used response types are:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Result&amp;lt;T, E&amp;gt;

Option&amp;lt;T&amp;gt;

HttpResponse (Web APIs)

impl Responder

ServiceResponse

Custom struct responses

JSON responses
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's understand each with syntax and examples.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Result Response
&lt;/h2&gt;

&lt;p&gt;The Result type is used when an operation may succeed or fail.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Syntax&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Result&amp;lt;T, E&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Where:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;T = success value
E = error value
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn divide(a: i32, b: i32) -&amp;gt; Result&amp;lt;i32, String&amp;gt; {

    if b == 0 {
        return Err("Cannot divide by zero".to_string());
    }

    Ok(a / b)
}

fn main() {

    let result = divide(10, 2);

    match result {
        Ok(value) =&amp;gt; println!("Result: {}", value),
        Err(e) =&amp;gt; println!("Error: {}", e),
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Output&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Result: 5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Option Response
&lt;/h2&gt;

&lt;p&gt;Option is used when a value may or may not exist.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Syntax&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Option&amp;lt;T&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Possible values:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
Some(value)
None
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn find_number(numbers: Vec&amp;lt;i32&amp;gt;, target: i32) -&amp;gt; Option&amp;lt;i32&amp;gt; {

    for n in numbers {
        if n == target {
            return Some(n);
        }
    }

    None
}

fn main() {

    let result = find_number(vec![1,2,3,4], 3);

    match result {
        Some(n) =&amp;gt; println!("Found: {}", n),
        None =&amp;gt; println!("Not found"),
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Output&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Found: 3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  HttpResponse (Web APIs)
&lt;/h2&gt;

&lt;p&gt;When building APIs using Actix-Web, responses are created using HttpResponse.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Syntax&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;HttpResponse::StatusCode().body(data)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use actix_web::{HttpResponse};

fn success_response() -&amp;gt; HttpResponse {
    HttpResponse::Ok().body("Request successful")
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Output&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Status: 200 OK
Body: Request successful
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  JSON Response
&lt;/h2&gt;

&lt;p&gt;Most APIs return JSON responses.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Syntax&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;HttpResponse::Ok().json(data)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use actix_web::HttpResponse;
use serde::Serialize;

#[derive(Serialize)]
struct User {
    name: String,
    age: u8
}

fn user_response() -&amp;gt; HttpResponse {

    let user = User {
        name: "Ashwani".to_string(),
        age: 30
    };

    HttpResponse::Ok().json(user)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example JSON Output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
 "name": "Ashwani",
 "age": 30
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  impl Responder
&lt;/h2&gt;

&lt;p&gt;Rust frameworks allow returning any type that implements Responder.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Syntax&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async fn handler() -&amp;gt; impl Responder
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use actix_web::{Responder, HttpResponse};

async fn hello() -&amp;gt; impl Responder {
    HttpResponse::Ok().body("Hello Rust")
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Output&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Hello Rust
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Custom Struct Response
&lt;/h2&gt;

&lt;p&gt;Sometimes we create structured responses for APIs.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Syntax&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct ApiResponse&amp;lt;T&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use serde::Serialize;

#[derive(Serialize)]
struct ApiResponse&amp;lt;T&amp;gt; {
    success: bool,
    data: T
}

fn main() {

    let response = ApiResponse {
        success: true,
        data: "User created"
    };

    println!("Success: {}", response.success);

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Output&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Success: true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  ServiceResponse (Middleware Response)
&lt;/h2&gt;

&lt;p&gt;When working with Actix middleware, responses are wrapped inside ServiceResponse.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Syntax&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ServiceResponse&amp;lt;B&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example concept:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ServiceRequest → Middleware → ServiceResponse
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Middleware may modify responses before sending them back to the client.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.debug.school/images/7QXym6rG4NjPQe3avAVHwWTtWFUalKGTzu-gaJbI5SY/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvcnY2YWtj/bm1neDdjYzBoY2N6/dmsucG5n" class="article-body-image-wrapper"&gt;&lt;img src="https://www.debug.school/images/7QXym6rG4NjPQe3avAVHwWTtWFUalKGTzu-gaJbI5SY/rt:fit/w:800/g:sm/q:0/mb:500000/ar:1/aHR0cHM6Ly93d3cu/ZGVidWcuc2Nob29s/L3VwbG9hZHMvYXJ0/aWNsZXMvcnY2YWtj/bm1neDdjYzBoY2N6/dmsucG5n" alt=" " width="762" height="412"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Objective and MCQ
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What is the most commonly used HTTP response type in Actix-web?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. ResponseData&lt;br&gt;
B. HttpResponse&lt;br&gt;
C. ServerResponse&lt;br&gt;
D. ApiResponse&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
HttpResponse is the primary type used to construct HTTP responses in Actix-web.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Which trait allows Actix handlers to return multiple response types&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Display&lt;br&gt;
B. Responder&lt;br&gt;
C. Clone&lt;br&gt;
D. Debug&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Handler functions can return any type implementing the Responder trait.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which method finalizes a response builder with body content?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. .finish()&lt;br&gt;
B. .body()&lt;br&gt;
C. .complete()&lt;br&gt;
D. .close()&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
.body() finalizes the HttpResponseBuilder with response content.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which method is used to send JSON data in an Actix response?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. .json()&lt;br&gt;
B. .data()&lt;br&gt;
C. .serialize()&lt;br&gt;
D. .send_json()&lt;/p&gt;

&lt;p&gt;✅ Answer: A&lt;br&gt;
.json() converts a structure to JSON response.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What does HttpResponse::Ok() represent?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. HTTP 200 response&lt;br&gt;
B. HTTP 404 response&lt;br&gt;
C. HTTP 500 response&lt;br&gt;
D. HTTP 201 response&lt;/p&gt;

&lt;p&gt;✅ Answer: A&lt;br&gt;
Ok() creates a response builder with status code 200.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which status code indicates resource creation?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. 200&lt;br&gt;
B. 201&lt;br&gt;
C. 404&lt;br&gt;
D. 500&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
HttpResponse::Created() represents status code 201.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Which HTTP response indicates authentication failure&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. 200&lt;br&gt;
B. 403&lt;br&gt;
C. 401&lt;br&gt;
D. 302&lt;/p&gt;

&lt;p&gt;✅ Answer: C&lt;br&gt;
401 Unauthorized indicates authentication failure.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which HTTP response indicates resource not found?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. 401&lt;br&gt;
B. 404&lt;br&gt;
C. 403&lt;br&gt;
D. 500&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
404 Not Found is returned when a resource is missing.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;What type is commonly used for JSON responses in Actix&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Json&lt;br&gt;
B. Map&lt;br&gt;
C. Data&lt;br&gt;
D. String&lt;/p&gt;

&lt;p&gt;✅ Answer: A&lt;br&gt;
Json serializes Rust structures into JSON responses.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which response type is used for plain text responses?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. HttpResponse::Ok().body("text")&lt;br&gt;
B. TextResponse&lt;br&gt;
C. StringResponse&lt;br&gt;
D. PlainResponse&lt;/p&gt;

&lt;p&gt;✅ Answer: A&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What does ServiceResponse represent?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Only HTTP body&lt;br&gt;
B. HTTP request + response wrapper&lt;br&gt;
C. Only HTTP headers&lt;br&gt;
D. Only status code&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
ServiceResponse wraps both the request and response objects.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Why are generics used in ServiceResponse&lt;b&gt;&lt;/b&gt;&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. To support multiple body types&lt;br&gt;
B. To increase performance only&lt;br&gt;
C. To store database values&lt;br&gt;
D. To reduce memory usage&lt;/p&gt;

&lt;p&gt;✅ Answer: A&lt;br&gt;
Generic B allows different body types in responses.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Which body type trait must response bodies implement&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Future&lt;br&gt;
B. MessageBody&lt;br&gt;
C. Serialize&lt;br&gt;
D. BodyTrait&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Actix requires response body types to implement MessageBody.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which type allows returning two possible response body types?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. DualBody&lt;br&gt;
B. EitherBody&lt;br&gt;
C. OptionalBody&lt;br&gt;
D. VariantBody&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
EitherBody allows two alternative body types.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Why is EitherBody useful in middleware?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. To reduce memory usage&lt;br&gt;
B. To return either middleware response or inner service response&lt;br&gt;
C. To store request data&lt;br&gt;
D. To parse JSON&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Middleware may return either its own response or the inner service response.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Which method converts body to a boxed type&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. box_body()&lt;br&gt;
B. map_into_boxed_body()&lt;br&gt;
C. convert_body()&lt;br&gt;
D. wrap_body()&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
This converts the response body into BoxBody.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which method changes the response body using a closure?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. map_response()&lt;br&gt;
B. map_body()&lt;br&gt;
C. convert_body()&lt;br&gt;
D. update_body()&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
map_body() transforms the response body type.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What is the purpose of HTTP response headers?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Store database values&lt;br&gt;
B. Provide metadata about the response&lt;br&gt;
C. Control server execution&lt;br&gt;
D. Encrypt responses&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which HTTP response indicates a server error?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. 404&lt;br&gt;
B. 403&lt;br&gt;
C. 500&lt;br&gt;
D. 201&lt;/p&gt;

&lt;p&gt;✅ Answer: C&lt;br&gt;
500 Internal Server Error indicates server failure.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Why are different response types used in Rust web APIs?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. To support various content formats and HTTP statuses&lt;br&gt;
B. To reduce Rust compilation time&lt;br&gt;
C. To remove middleware&lt;br&gt;
D. To simplify database queries&lt;/p&gt;

&lt;p&gt;✅ Answer: A&lt;br&gt;
Different response types allow APIs to return JSON, text, HTML, or error responses depending on the situation.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>why Rust futures must be pinned</title>
      <dc:creator>rakesh kumar</dc:creator>
      <pubDate>Thu, 05 Mar 2026 23:39:32 +0000</pubDate>
      <link>https://www.debug.school/rakeshdevcotocus_468/why-rust-futures-must-be-pinned-280</link>
      <guid>https://www.debug.school/rakeshdevcotocus_468/why-rust-futures-must-be-pinned-280</guid>
      <description>&lt;p&gt;.&lt;strong&gt;What is Box in Rust?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Why Heap Memory is Useful&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;What is Pin?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;What is Box::pin?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Why Box::pin is Used in Async Code&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Why Box::pin is Needed in Middleware&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Objective and mcq&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;What is Box

What is Pin

Why Box::pin is needed
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What is Box in Rust?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A Box stores a value on the heap memory instead of the stack.&lt;/p&gt;

&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn main() {

    let a = 10;              // stored on stack
    let b = Box::new(20);    // stored on heap

    println!("a = {}", a);
    println!("b = {}", b);

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Output&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a = 10
b = 20
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a → stack memory
b → heap memory
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rust moves large or dynamic data to the heap using Box.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Why Heap Memory is Useful&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Stack memory must know exact size at compile time.&lt;/p&gt;

&lt;p&gt;But sometimes Rust needs dynamic memory.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async futures

recursive types

large data structures
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So we use:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Box&amp;lt;T&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What is Pin?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Pin means a value cannot move in memory after being placed somewhere.&lt;/p&gt;

&lt;p&gt;Why?&lt;/p&gt;

&lt;p&gt;Some async operations depend on memory not changing location.&lt;/p&gt;

&lt;p&gt;Think of it like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Pin = Fix the object in memory
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example analogy:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Stack variable → movable
Pinned variable → fixed position
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;What is Box::pin?&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Box::pin does two things together:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Stores the value in heap memory&lt;/p&gt;

&lt;p&gt;Pins the value so it cannot move&lt;/p&gt;

&lt;p&gt;So:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Box::pin(value)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;means:&lt;/p&gt;

&lt;p&gt;Put value on heap&lt;br&gt;
and fix its memory location&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Basic Example of Box::pin&lt;/strong&gt;
Code
use std::pin::Pin;
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn main() {

    let value = Box::pin(100);

    println!("Pinned value = {}", value);

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;`Output`
Pinned value = 100
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Here:&lt;/p&gt;

&lt;p&gt;100 → stored on heap&lt;br&gt;
and pinned&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Why Box::pin is Used in Async Code&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Async functions create Future objects.&lt;/p&gt;

&lt;p&gt;Example async function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async fn say_hello() {
    println!("Hello from async function");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function actually returns a Future.&lt;/p&gt;

&lt;p&gt;But Rust cannot easily store unknown-sized futures.&lt;/p&gt;

&lt;p&gt;So we wrap them using:&lt;/p&gt;

&lt;p&gt;Box::pin(future)&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Simple Async Example&lt;/strong&gt;
Code
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use std::future::Future;
use std::pin::Pin;

async fn greet() {
    println!("Hello Rust");
}

fn main() {

    let future: Pin&amp;lt;Box&amp;lt;dyn Future&amp;lt;Output = ()&amp;gt;&amp;gt;&amp;gt; = Box::pin(greet());

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Explanation&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Box → store future on heap
Pin → future cannot move
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Example Similar to Actix Middleware&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Actix middleware returns this type:&lt;/p&gt;

&lt;p&gt;LocalBoxFuture&amp;lt;'static, Result&amp;gt;&lt;/p&gt;

&lt;p&gt;This is usually created like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Box::pin(async move {

    println!("Middleware running");

    Ok(response)

})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use std::future::Future;
use std::pin::Pin;

fn main() {

    let future = Box::pin(async {

        println!("Async task running");

    });

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output (when executed)&lt;br&gt;
Async task running&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Why Box::pin is Needed in Middleware&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In Actix middleware we often see:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn call(&amp;amp;self, req: ServiceRequest) -&amp;gt; Self::Future {

    Box::pin(async move {

        println!("Middleware executing");

    })
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Why?&lt;/p&gt;

&lt;p&gt;Because:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async block → creates a Future
Future size → unknown at compile time
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So Rust requires:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Box::pin(async block)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;to place it safely on heap.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Simple Visualization&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Without Box::pin&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async block
   ↓
Unknown size future
   ↓
Rust cannot store it

With Box::pin

async block
   ↓
Future
   ↓
Box (heap storage)
   ↓
Pinned memory location
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Real World Analogy&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Think of memory like a parking lot.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Normal variable:&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Car parked temporarily
It can move anytime
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Pinned variable:&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Car fixed in a reserved parking slot
Cannot move
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Box::pin does exactly this.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Small Practical Example&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use std::pin::Pin;

fn main() {

    let data = Box::pin(String::from("Rust Programming"));

    println!("{}", data);

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Output&lt;/code&gt;&lt;br&gt;
Rust Programming&lt;/p&gt;

&lt;p&gt;Here:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;String stored in heap
Pinned to fixed location

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When working with async programming in Rust, you often see concepts like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Pin

Box::pin

Future
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Many developers ask:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why do Rust futures need to be pinned?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The reason is connected to how async functions work internally.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What an Async Function Actually Returns&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;When you write this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async fn hello() {
    println!("Hello Rust");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rust does not immediately run the function.&lt;/p&gt;

&lt;p&gt;Instead, Rust converts it into a Future.&lt;/p&gt;

&lt;p&gt;Conceptually it becomes something like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn hello() -&amp;gt; impl Future&amp;lt;Output = ()&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So an async function returns a Future object.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Futures Work Like State Machines&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Rust transforms async code into a state machine.&lt;/p&gt;

&lt;p&gt;Example async code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async fn example() {
    step1().await;
    step2().await;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Internally Rust converts this into something like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;State 0 → Start
State 1 → After step1
State 2 → After step2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each await point stores data inside the future struct.&lt;/p&gt;

&lt;p&gt;So the future keeps internal references to its own memory.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;The Problem: Moving Futures in Memory&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Normally in Rust, values can move in memory.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn main() {

    let a = String::from("Rust");

    let b = a; // moved

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When values move:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Old memory → invalid
New memory → new location
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is normally safe.&lt;/p&gt;

&lt;p&gt;But for futures it creates a problem.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;The Self-Reference Problem&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Async futures may contain references to their own internal fields.&lt;/p&gt;

&lt;p&gt;Example conceptually:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Future Struct&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
field1: String
field2: reference to field1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Visual example:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Memory location: 0x1000&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;field1 → "hello"
field2 → reference to 0x1000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now imagine the future moves to another location:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;New memory: 0x2000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But the reference still points to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;0x1000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Which is now invalid.&lt;/p&gt;

&lt;p&gt;This causes memory safety issues.&lt;/p&gt;

&lt;p&gt;Rust prevents this by pinning the future.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What Pinning Does&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;code&gt;Pinning means:&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Once placed in memory → cannot move&lt;/p&gt;

&lt;p&gt;So if a future is pinned:&lt;/p&gt;

&lt;p&gt;Future memory address stays fixed&lt;/p&gt;

&lt;p&gt;This guarantees that internal references remain valid.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Example Without Pin (Conceptual Problem)&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Consider this conceptual future:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct MyFuture {
    data: String,
    reference: *const String,
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the struct moves:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
data moves to new location
reference still points to old location

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This breaks memory safety.&lt;/p&gt;

&lt;p&gt;Rust avoids this by requiring:&lt;/p&gt;

&lt;p&gt;Pinned Futures&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Simple Example of Pin&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use std::pin::Pin;

fn main() {

    let value = Box::pin(10);

    println!("Pinned value: {}", value);

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Output&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Pinned value: 10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here:&lt;/p&gt;

&lt;p&gt;10 &lt;strong&gt;is stored on heap&lt;/strong&gt;&lt;br&gt;
and pinned so it cannot move&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Async Example with Pin&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use std::future::Future;
use std::pin::Pin;

async fn say_hello() {
    println!("Hello Rust Async");
}

fn main() {

    let future: Pin&amp;lt;Box&amp;lt;dyn Future&amp;lt;Output = ()&amp;gt;&amp;gt;&amp;gt; =
        Box::pin(say_hello());

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Here:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Future stored on heap
Future pinned
Memory location fixed
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Why Middleware Uses Box::pin&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A Box stores a value on the heap memory instead of the stack.&lt;/p&gt;

&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn main() {

    let a = 10;              // stored on stack
    let b = Box::new(20);    // stored on heap

    println!("a = {}", a);
    println!("b = {}", b);

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Output&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a = 10
b = 20
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a → stack memory
b → heap memory
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rust moves large or dynamic data to the heap using Box.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;In Actix middleware you often see:&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Box::pin(async move {

    println!("Middleware running");

})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Why?&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Because&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async block → creates a Future
Future size → unknown
Future may contain self references
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So Rust requires:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Box::pin(async block)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;to safely store and pin it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Heap Memory is Useful&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Stack memory must know exact size at compile time.

But sometimes Rust needs dynamic memory.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Example&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async futures

recursive types

large data structures

So we use:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Box&amp;lt;T&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Visual Summary&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;code&gt;Without pinning:&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Future
  │
  ▼
Memory moves
  │
  ▼
Internal references break

`With pinning:`

Future
  │
  ▼
Pinned memory location
  │
  ▼
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;References remain valid&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Real-World Analogy&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Imagine a map with a location marker.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Normal variable:&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;House moves → map still points to old place
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Pinned variable:&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;House fixed → map always correct
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pinning ensures that the address never changes.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;When Futures Must Be Pinned&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Futures must be pinned when:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;they contain self-references

they are polled multiple times

they are stored in heap structures

they are used in async frameworks
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Actix Web
Tokio
Hyper
Async executors
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Key Takeaway&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Rust futures must be pinned because:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Async futures may contain references to their own internal memory.
If the future moves, those references break.
Pinning prevents movement and keeps memory safe.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;What is the main purpose of pinning a future in Rust?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A. Increase execution speed&lt;br&gt;
B. Prevent the future from moving in memory&lt;br&gt;
C. Allow multiple threads to run&lt;br&gt;
D. Reduce compilation time&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Pinning guarantees the value will not move in memory.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Why do many Rust futures require pinning&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Futures require heap allocation&lt;br&gt;
B. Futures often contain self-references&lt;br&gt;
C. Futures cannot use references&lt;br&gt;
D. Futures always run in parallel&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Many futures are self-referential, so they must stay in a fixed memory location.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What happens if a self-referential future moves in memory?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Execution becomes faster&lt;br&gt;
B. References become invalid&lt;br&gt;
C. Memory is automatically fixed&lt;br&gt;
D. Nothing happens&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Moving such a structure breaks internal references.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Which Rust type ensures a value cannot move after being pinned&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Future&lt;br&gt;
B. Pin&lt;br&gt;
C. Box&lt;br&gt;
D. Ref&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Pin&lt;/p&gt;
&lt;p&gt; guarantees the pointed value will not move.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;W*&lt;em&gt;hich trait indicates that a type can safely move even if pinned?&lt;/em&gt;*&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Copy&lt;br&gt;
B. Send&lt;br&gt;
C. Unpin&lt;br&gt;
D. Clone&lt;/p&gt;

&lt;p&gt;✅ Answer: C&lt;br&gt;
Unpin means the value can move safely even when wrapped in Pin.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What does the Future::poll() method require as its first parameter?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. &amp;amp;Self&lt;br&gt;
B. Pin&amp;lt;&amp;amp;mut Self&amp;gt;&lt;br&gt;
C. Box&lt;br&gt;
D. Self&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
The future must be pinned before polling.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Why does poll() require Pin&amp;lt;&amp;amp;mut Self&amp;gt;?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. To allow multiple threads&lt;br&gt;
B. To guarantee the future will not move&lt;br&gt;
C. To increase performance&lt;br&gt;
D. To reduce memory&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Pinning ensures safe polling of self-referential futures.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;What does async/await compile into internally&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Threads&lt;br&gt;
B. State machines&lt;br&gt;
C. Processes&lt;br&gt;
D. Channels&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Async functions are compiled into state machines.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Why can async state machines become self-referential&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. They store references across .await points&lt;br&gt;
B. They allocate memory on heap&lt;br&gt;
C. They use threads&lt;br&gt;
D. They call external libraries&lt;/p&gt;

&lt;p&gt;✅ Answer: A&lt;br&gt;
Variables stored across await points may reference each other.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;What does pinning guarantee about a future’s memory address&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. It changes frequently&lt;br&gt;
B. It remains constant&lt;br&gt;
C. It moves automatically&lt;br&gt;
D. It becomes static&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Pinning keeps the memory location fixed.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which function is commonly used to pin a future on the heap?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Box::new()&lt;br&gt;
B. Box::pin()&lt;br&gt;
C. Pin::wrap()&lt;br&gt;
D. Future::pin()&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;What kind of data structure often requires pinning?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Numeric values&lt;br&gt;
B. Self-referential structures&lt;br&gt;
C. Static variables&lt;br&gt;
D. Boolean flags&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Self-referential data must remain at a fixed location.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Which Rust feature generates futures automatically?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. match&lt;br&gt;
B. async fn&lt;br&gt;
C. loop&lt;br&gt;
D. impl&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Which keyword waits for a future to complete&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. wait&lt;br&gt;
B. future&lt;br&gt;
C. await&lt;br&gt;
D. async&lt;/p&gt;

&lt;p&gt;✅ Answer: C&lt;/p&gt;

&lt;p&gt;15.** What problem does pinning primarily prevent?**&lt;/p&gt;

&lt;p&gt;A. CPU overload&lt;br&gt;
B. Dangling references&lt;br&gt;
C. Thread starvation&lt;br&gt;
D. Compilation errors&lt;/p&gt;

&lt;p&gt;✅ Answer: B&lt;br&gt;
Moving self-referential futures could create dangling pointers.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Which pointer types can be wrapped by Pin&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Only Box&lt;br&gt;
B. Only &amp;amp;T&lt;br&gt;
C. Pointer types like &amp;amp;mut T or Box&lt;br&gt;
D. Only Vec&lt;/p&gt;

&lt;p&gt;✅ Answer: C&lt;br&gt;
Pin wraps pointer types to prevent movement.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;When should a future typically be pinned?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Before it is polled&lt;br&gt;
B. After execution completes&lt;br&gt;
C. After compilation&lt;br&gt;
D. Before writing code&lt;/p&gt;

&lt;p&gt;✅ Answer: A&lt;br&gt;
Futures must be pinned before polling begins.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Which scenario allows a pinned value to still move safely&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. If the type implements Unpin&lt;br&gt;
B. If the future is async&lt;br&gt;
C. If the value is boxed&lt;br&gt;
D. If the runtime moves it&lt;/p&gt;

&lt;p&gt;✅ Answer: A&lt;br&gt;
Unpin indicates movement is safe even when pinned.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;What is the relationship between Pin and async runtimes&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Runtimes require pinned futures for safe polling&lt;br&gt;
B. Runtimes ignore pinning&lt;br&gt;
C. Pinning disables async runtime&lt;br&gt;
D. Pinning removes futures&lt;/p&gt;

&lt;p&gt;✅ Answer: A&lt;br&gt;
Executors rely on pinned futures for safe execution.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;What is the key concept behind pinning in Rust async programming&lt;/strong&gt;?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A. Memory stability for asynchronous tasks&lt;br&gt;
B. Faster execution&lt;br&gt;
C. Smaller binaries&lt;br&gt;
D. Thread synchronization&lt;/p&gt;

&lt;p&gt;✅ Answer: A&lt;br&gt;
Pinning ensures memory stability and safe async execution.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Security Headers Middleware in Actix-Web (Rust)</title>
      <dc:creator>rakesh kumar</dc:creator>
      <pubDate>Thu, 05 Mar 2026 14:06:29 +0000</pubDate>
      <link>https://www.debug.school/rakeshdevcotocus_468/security-headers-middleware-in-actix-web-rust-1j07</link>
      <guid>https://www.debug.school/rakeshdevcotocus_468/security-headers-middleware-in-actix-web-rust-1j07</guid>
      <description>&lt;p&gt;Production-ready theory + step-by-step code flow (main.rs → middleware → handler → db)&lt;/p&gt;

&lt;p&gt;Security headers are HTTP response headers that tell browsers how to behave. They reduce common attacks like XSS, clickjacking, MIME sniffing, and data leakage. In a Rust/Actix backend, the clean way is to apply these headers using middleware, so every response gets the same secure defaults without repeating code in each handler.&lt;/p&gt;

&lt;p&gt;In this blog, you will build a custom Security Headers middleware and wire it into main.rs. You’ll also see the request flow: middleware runs, handler executes, DB query runs, then middleware adds headers to the response.&lt;/p&gt;

&lt;p&gt;1) &lt;strong&gt;What are security headers?&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;What&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Security headers are response headers that enforce browser security rules.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Why&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;They reduce risk from:

Cross-site scripting (XSS)

Clickjacking (UI redress attacks)

MIME-type sniffing (wrong content treated as executable)

Referrer leakage

Insecure resource loading
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;When&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Use security headers on:

All API responses (safe defaults)

Any server that serves HTML pages or assets

Admin dashboards and user-facing sites
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Even if you return JSON only, these headers are still beneficial.&lt;/p&gt;

&lt;p&gt;2) &lt;strong&gt;Request flow (middleware → handler → DB → middleware)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A secure request looks like this:&lt;/p&gt;

&lt;p&gt;Client calls GET /api/shops&lt;/p&gt;

&lt;p&gt;Middleware receives request&lt;/p&gt;

&lt;p&gt;Middleware forwards request to handler&lt;/p&gt;

&lt;p&gt;Handler checks session and calls DB&lt;/p&gt;

&lt;p&gt;Handler returns JSON response&lt;/p&gt;

&lt;p&gt;Middleware adds security headers to response&lt;/p&gt;

&lt;p&gt;Response goes back to client&lt;/p&gt;

&lt;p&gt;This ensures every response is protected automatically.&lt;/p&gt;

&lt;p&gt;3) &lt;strong&gt;Step 1: Decide which headers to set&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Below is a good production default:&lt;/p&gt;

&lt;p&gt;✅ X-Content-Type-Options: nosniff&lt;br&gt;
Prevents MIME sniffing.&lt;/p&gt;

&lt;p&gt;✅ X-Frame-Options: DENY&lt;br&gt;
Blocks clickjacking (no iframe embedding).&lt;/p&gt;

&lt;p&gt;✅ Referrer-Policy: no-referrer (or strict-origin-when-cross-origin)&lt;br&gt;
Reduces referrer leakage.&lt;/p&gt;

&lt;p&gt;✅ Permissions-Policy: ...&lt;br&gt;
Disables browser features you don’t use (camera, mic, etc).&lt;/p&gt;

&lt;p&gt;✅ Strict-Transport-Security (HSTS)&lt;br&gt;
Force HTTPS, but only in production with real TLS.&lt;/p&gt;

&lt;p&gt;✅ Content-Security-Policy (CSP)&lt;br&gt;
Powerful header for XSS control (more relevant when serving HTML). For pure JSON APIs you can still set a safe CSP, but it matters most when you return pages.&lt;/p&gt;

&lt;p&gt;4) &lt;strong&gt;Step 2: Create Security Headers middleware&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;src/middleware/security_headers.rs

use actix_service::{Service, Transform};
use actix_web::{
    dev::{ServiceRequest, ServiceResponse},
    http::header::{HeaderName, HeaderValue},
    Error,
};
use futures_util::future::{ready, LocalBoxFuture, Ready};

#[derive(Clone)]
pub struct SecurityHeaders {
    // enable HSTS only in production
    pub enable_hsts: bool,
    // optional CSP if you serve HTML
    pub csp: Option&amp;lt;String&amp;gt;,
}

impl SecurityHeaders {
    pub fn new(enable_hsts: bool, csp: Option&amp;lt;String&amp;gt;) -&amp;gt; Self {
        Self { enable_hsts, csp }
    }
}

impl&amp;lt;S, B&amp;gt; Transform&amp;lt;S, ServiceRequest&amp;gt; for SecurityHeaders
where
    S: Service&amp;lt;ServiceRequest, Response = ServiceResponse&amp;lt;B&amp;gt;, Error = Error&amp;gt; + 'static,
    B: 'static,
{
    type Response = ServiceResponse&amp;lt;B&amp;gt;;
    type Error = Error;
    type Transform = SecurityHeadersMiddleware&amp;lt;S&amp;gt;;
    type InitError = ();
    type Future = Ready&amp;lt;Result&amp;lt;Self::Transform, Self::InitError&amp;gt;&amp;gt;;

    fn new_transform(&amp;amp;self, service: S) -&amp;gt; Self::Future {
        ready(Ok(SecurityHeadersMiddleware {
            service,
            cfg: self.clone(),
        }))
    }
}

pub struct SecurityHeadersMiddleware&amp;lt;S&amp;gt; {
    service: S,
    cfg: SecurityHeaders,
}

impl&amp;lt;S, B&amp;gt; Service&amp;lt;ServiceRequest&amp;gt; for SecurityHeadersMiddleware&amp;lt;S&amp;gt;
where
    S: Service&amp;lt;ServiceRequest, Response = ServiceResponse&amp;lt;B&amp;gt;, Error = Error&amp;gt; + 'static,
    B: 'static,
{
    type Response = ServiceResponse&amp;lt;B&amp;gt;;
    type Error = Error;
    type Future = LocalBoxFuture&amp;lt;'static, Result&amp;lt;Self::Response, Self::Error&amp;gt;&amp;gt;;

    fn call(&amp;amp;self, req: ServiceRequest) -&amp;gt; Self::Future {
        let cfg = self.cfg.clone();
        let fut = self.service.call(req);

        Box::pin(async move {
            let mut res = fut.await?;

            // 1) No MIME sniffing
            res.headers_mut().insert(
                HeaderName::from_static("x-content-type-options"),
                HeaderValue::from_static("nosniff"),
            );

            // 2) Block iframe embedding (clickjacking)
            res.headers_mut().insert(
                HeaderName::from_static("x-frame-options"),
                HeaderValue::from_static("deny"),
            );

            // 3) Reduce referrer leakage
            res.headers_mut().insert(
                HeaderName::from_static("referrer-policy"),
                HeaderValue::from_static("strict-origin-when-cross-origin"),
            );

            // 4) Browser features control
            res.headers_mut().insert(
                HeaderName::from_static("permissions-policy"),
                HeaderValue::from_static("camera=(), microphone=(), geolocation=(), payment=()"),
            );

            // 5) HSTS only for production HTTPS
            if cfg.enable_hsts {
                res.headers_mut().insert(
                    HeaderName::from_static("strict-transport-security"),
                    HeaderValue::from_static("max-age=31536000; includeSubDomains"),
                );
            }

            // 6) Optional CSP (mainly for HTML pages)
            if let Some(csp) = cfg.csp {
                if let Ok(v) = HeaderValue::from_str(&amp;amp;csp) {
                    res.headers_mut().insert(
                        HeaderName::from_static("content-security-policy"),
                        v,
                    );
                }
            }

            Ok(res)
        })
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;2–3 simple lines about what this does&lt;/p&gt;

&lt;p&gt;This middleware runs after your handler returns a response. It then injects security headers into every response automatically. This means you don’t need to add headers in each handler.&lt;/p&gt;

&lt;p&gt;5) &lt;strong&gt;Step 3: Register middleware module&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
src/middleware/mod.rs
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;pub mod security_headers;&lt;br&gt;
6) S*&lt;em&gt;tep 4: Wire it into main.rs&lt;/em&gt;*&lt;/p&gt;

&lt;p&gt;In main.rs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mod middleware;
use middleware::security_headers::SecurityHeaders;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Enable HSTS only in production:&lt;/p&gt;

&lt;p&gt;let is_production = std::env::var("APP_ENV").unwrap_or_default() == "production";&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// If you serve only JSON, CSP can be optional.
// If you serve HTML templates, set a real CSP.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;let csp = Some("default-src 'self'; frame-ancestors 'none'; base-uri 'self'".to_string());&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
HttpServer::new(move || {
    App::new()
        .app_data(state.clone())
        .wrap(cors)
        .wrap(
            SessionMiddleware::builder(CookieSessionStore::default(), key.clone())
                .cookie_secure(is_production)
                .cookie_same_site(SameSite::Lax)
                .build(),
        )
        // ✅ Security headers middleware
        .wrap(SecurityHeaders::new(is_production, csp.clone()))
        .service(
            web::scope("/api")
                .route("/shops", web::get().to(handlers::list_shops_handler))
                .route("/login", web::post().to(handlers::login))
        )
        .service(Files::new("/uploads", "./uploads"))
})
.bind(cfg.bind_addr)?
.run()
.await
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Why .wrap(SecurityHeaders...) is placed here&lt;/p&gt;

&lt;p&gt;Because it should apply to all responses under the app. Any handler that returns JSON will automatically include these security headers.&lt;/p&gt;

&lt;p&gt;7) &lt;strong&gt;Step 5: Handler example that hits DB&lt;/strong&gt;&lt;br&gt;
handlers/shop.rs&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use actix_session::Session;
use actix_web::{error, web, HttpResponse, Result};

use crate::db::{list_shops_by_vendor, AppState};
use super::common::{ensure_login_user_id, ApiResponse};

pub async fn list_shops_handler(
    state: web::Data&amp;lt;AppState&amp;gt;,
    session: Session,
) -&amp;gt; Result&amp;lt;HttpResponse&amp;gt; {
    // Auth check
    let user_id = ensure_login_user_id(&amp;amp;session)?;

    let vendor_id = i32::try_from(user_id).map_err(|_| error::ErrorBadRequest("User id invalid"))?;

    // DB call
    let shops = list_shops_by_vendor(&amp;amp;state.pool, vendor_id)
        .await
        .map_err(error::ErrorInternalServerError)?;

    // Response
    Ok(HttpResponse::Ok().json(ApiResponse {
        message: "Shops fetched".to_string(),
        data: shops,
    }))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;DB function (example)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;db/shop.rs&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use sqlx::MySqlPool;

pub async fn list_shops_by_vendor(pool: &amp;amp;MySqlPool, vendor_id: i32) -&amp;gt; Result&amp;lt;Vec&amp;lt;Shop&amp;gt;, sqlx::Error&amp;gt; {
    let rows = sqlx::query_as::&amp;lt;_, Shop&amp;gt;("SELECT * FROM shops WHERE vendor_id = ?")
        .bind(vendor_id)
        .fetch_all(pool)
        .await?;

    Ok(rows)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;8) &lt;strong&gt;Confirm headers in browser/network&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Call:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
curl -i http://127.0.0.1:8080/api/shops
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should see headers like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;X-Content-Type-Options: nosniff
X-Frame-Options: deny
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=()
Strict-Transport-Security: max-age=31536000; includeSubDomains   (only production)
Content-Security-Policy: default-src 'self'; frame-ancestors 'none'; base-uri 'self'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;9) &lt;strong&gt;Production tips (important)&lt;/strong&gt;&lt;br&gt;
Use HSTS only when HTTPS is guaranteed&lt;/p&gt;

&lt;p&gt;If you enable HSTS on a domain that sometimes serves HTTP, users may get locked out.&lt;/p&gt;

&lt;p&gt;Be careful with CSP&lt;/p&gt;

&lt;p&gt;If you serve frontend HTML, CSP needs to allow required scripts/styles. For API-only backend, CSP is optional.&lt;/p&gt;

&lt;p&gt;Add Cache-Control: no-store for auth endpoints&lt;/p&gt;

&lt;p&gt;For login/session sensitive endpoints:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;res.headers_mut().insert(
    HeaderName::from_static("cache-control"),
    HeaderValue::from_static("no-store"),
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Rate Limiting Middleware in Actix-Web (Rust)</title>
      <dc:creator>rakesh kumar</dc:creator>
      <pubDate>Thu, 05 Mar 2026 13:58:40 +0000</pubDate>
      <link>https://www.debug.school/rakeshdevcotocus_468/rate-limiting-middleware-in-actix-web-rust-n1p</link>
      <guid>https://www.debug.school/rakeshdevcotocus_468/rate-limiting-middleware-in-actix-web-rust-n1p</guid>
      <description>&lt;p&gt;&lt;strong&gt;What rate limiting does(What/When/Why/Flow of a rate-limited request)&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Request flow (middleware → handler → DB → middleware)&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Step 1: Decide which headers to set&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Step 2: Create rate limiter middleware&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Step 3: Wire middleware in main.rs&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Step 4: Handler example (login) showing DB flow&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Step 5: Make rate limiting stricter only for login (best practice)&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Production notes (very important)&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Practical Example&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Rate limiting means “don’t allow one client to hit the same API too many times in a short time.” It protects your server from brute-force login attempts, abusive bots, and accidental traffic spikes. In session-based apps, rate limiting is especially useful for endpoints like /login, /register, /otp, /search, and any expensive DB query route.&lt;/p&gt;

&lt;p&gt;In this blog, we’ll build a custom rate limiting middleware (no external service needed), wire it in main.rs, and show how it blocks requests before they reach handler + DB.&lt;/p&gt;
&lt;h2&gt;
  
  
  What rate limiting does
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;What&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It limits requests per key (IP, user_id, or API token) per time window.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Stops brute-force attacks on /login

Reduces DB load

Avoids abuse (spam, scraping)

Improves uptime
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;When&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Always on login and OTP routes

On public listing endpoints that can be scraped

On file upload endpoints (to avoid storage abuse)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Flow of a rate-limited request&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;Request flow&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Client hits /api/login

Middleware runs first

Middleware checks “how many requests from this key in last X seconds”

If allowed → request goes to handler → handler calls DB

If blocked → middleware returns 429 Too Many Requests and handler/DB never runs
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;3) &lt;strong&gt;Step 1: Add required dependencies&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In Cargo.toml:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# For time + thread-safe shared state
chrono = "0.4"
tokio = { version = "1", features = ["sync"] }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(You already use tokio and chrono; if yes, no changes.)&lt;/p&gt;

&lt;p&gt;4) &lt;strong&gt;Step 2: Create rate limiter middleware&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;src/middleware/rate_limit.rs
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This version implements a fixed window counter:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;window: 60 seconds
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;max requests: 10 per window per IP per route (customizable)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use actix_service::{Service, Transform};
use actix_web::{
    dev::{ServiceRequest, ServiceResponse},
    error,
    http::StatusCode,
    Error, HttpResponse,
};
use chrono::Utc;
use futures_util::future::{ready, LocalBoxFuture, Ready};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::Mutex;

/// Simple in-memory rate limiter state.
/// Key example: "IP|METHOD|PATH"
#[derive(Clone)]
pub struct RateLimiter {
    pub state: Arc&amp;lt;Mutex&amp;lt;HashMap&amp;lt;String, Counter&amp;gt;&amp;gt;&amp;gt;,
    pub window_secs: i64,
    pub max_requests: u32,
}

#[derive(Debug, Clone)]
pub struct Counter {
    pub window_start: i64,
    pub count: u32,
}

impl RateLimiter {
    pub fn new(window_secs: i64, max_requests: u32) -&amp;gt; Self {
        Self {
            state: Arc::new(Mutex::new(HashMap::new())),
            window_secs,
            max_requests,
        }
    }
}

/// Middleware wrapper object
pub struct RateLimitMiddleware {
    limiter: RateLimiter,
}

impl RateLimitMiddleware {
    pub fn new(limiter: RateLimiter) -&amp;gt; Self {
        Self { limiter }
    }
}

impl&amp;lt;S, B&amp;gt; Transform&amp;lt;S, ServiceRequest&amp;gt; for RateLimitMiddleware
where
    S: Service&amp;lt;ServiceRequest, Response = ServiceResponse&amp;lt;B&amp;gt;, Error = Error&amp;gt; + 'static,
    B: 'static,
{
    type Response = ServiceResponse&amp;lt;B&amp;gt;;
    type Error = Error;
    type Transform = RateLimitMiddlewareService&amp;lt;S&amp;gt;;
    type InitError = ();
    type Future = Ready&amp;lt;Result&amp;lt;Self::Transform, Self::InitError&amp;gt;&amp;gt;;

    fn new_transform(&amp;amp;self, service: S) -&amp;gt; Self::Future {
        ready(Ok(RateLimitMiddlewareService {
            service,
            limiter: self.limiter.clone(),
        }))
    }
}

pub struct RateLimitMiddlewareService&amp;lt;S&amp;gt; {
    service: S,
    limiter: RateLimiter,
}

impl&amp;lt;S, B&amp;gt; Service&amp;lt;ServiceRequest&amp;gt; for RateLimitMiddlewareService&amp;lt;S&amp;gt;
where
    S: Service&amp;lt;ServiceRequest, Response = ServiceResponse&amp;lt;B&amp;gt;, Error = Error&amp;gt; + 'static,
    B: 'static,
{
    type Response = ServiceResponse&amp;lt;B&amp;gt;;
    type Error = Error;
    type Future = LocalBoxFuture&amp;lt;'static, Result&amp;lt;Self::Response, Self::Error&amp;gt;&amp;gt;;

    fn call(&amp;amp;self, req: ServiceRequest) -&amp;gt; Self::Future {
        let limiter = self.limiter.clone();

        // Identify client (basic: IP). If behind proxy, you’ll read X-Forwarded-For safely.
        let ip = req
            .connection_info()
            .realip_remote_addr()
            .unwrap_or("unknown")
            .to_string();

        // Per endpoint key
        let key = format!("{}|{}|{}", ip, req.method(), req.path());

        let fut = self.service.call(req);

        Box::pin(async move {
            let now = Utc::now().timestamp();

            // Check + update counter
            let mut map = limiter.state.lock().await;
            let counter = map.entry(key).or_insert(Counter {
                window_start: now,
                count: 0,
            });

            // Reset window if expired
            if now - counter.window_start &amp;gt;= limiter.window_secs {
                counter.window_start = now;
                counter.count = 0;
            }

            // Increment and decide
            counter.count += 1;

            if counter.count &amp;gt; limiter.max_requests {
                // Block request with 429
                let res = HttpResponse::build(StatusCode::TOO_MANY_REQUESTS).json(serde_json::json!({
                    "success": false,
                    "message": "Too many requests. Please try again later.",
                    "code": 429
                }));
                return Err(error::InternalError::from_response("", res).into());
            }

            // Allowed → continue
            fut.await
        })
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notes (simple, practical)&lt;/p&gt;

&lt;p&gt;This is in-memory rate limiting. It works well for single server.&lt;/p&gt;

&lt;p&gt;For multi-server (multiple instances), you’d store counters in Redis (same logic, shared store).&lt;/p&gt;

&lt;p&gt;5) &lt;strong&gt;Step 3: Wire middleware in main.rs&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create module file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;src/middleware/mod.rs
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;pub mod rate_limit;&lt;/p&gt;

&lt;p&gt;Now in main.rs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mod middleware;
use middleware::rate_limit::{RateLimiter, RateLimitMiddleware};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add it to your app. Example: allow 10 requests per 60 seconds per IP per endpoint.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;HttpServer::new(move || {
    let limiter = RateLimiter::new(60, 10);

    App::new()
        .app_data(state.clone())
        .wrap(cors)
        .wrap(
            SessionMiddleware::builder(CookieSessionStore::default(), key.clone())
                .cookie_secure(false)
                .cookie_same_site(SameSite::Lax)
                .build(),
        )
        // Rate limit runs before handlers
        .wrap(RateLimitMiddleware::new(limiter))
        .service(
            web::scope("/api")
                .route("/login", web::post().to(handlers::login))
                .route("/shops", web::get().to(handlers::list_shops_handler))
        )
        .service(Files::new("/uploads", "./uploads"))
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Important middleware order&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;CORS and Session can be before rate limit.&lt;/p&gt;

&lt;p&gt;Rate limit should be early enough that it blocks before heavy work.&lt;/p&gt;

&lt;p&gt;6) &lt;strong&gt;Step 4: Handler example (login) showing DB flow&lt;/strong&gt;&lt;br&gt;
Handler&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;src/handlers/auth.rs (simplified)

use actix_session::Session;
use actix_web::{error, web, HttpResponse, Result};
use crate::db::{find_user_by_username, AppState};
use crate::models::LoginForm;
use super::common::ApiResponse;

pub async fn login(
    body: web::Json&amp;lt;LoginForm&amp;gt;,
    state: web::Data&amp;lt;AppState&amp;gt;,
    session: Session,
) -&amp;gt; Result&amp;lt;HttpResponse&amp;gt; {
    // If rate limit blocks, this handler will never run.

    let user = find_user_by_username(&amp;amp;state.pool, &amp;amp;body.username)
        .await
        .map_err(error::ErrorInternalServerError)?;

    if let Some(user) = user {
        let valid = user.password == body.password;
        if valid {
            session.insert("user_id", user.id).map_err(error::ErrorInternalServerError)?;
            session.insert("username", user.username.clone()).map_err(error::ErrorInternalServerError)?;
            session.insert("role", user.role.clone()).map_err(error::ErrorInternalServerError)?;

            return Ok(HttpResponse::Ok().json(ApiResponse {
                message: "Login successful".to_string(),
                data: true,
            }));
        }
    }

    Err(error::ErrorUnauthorized("Invalid credentials"))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;DB function&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;src/db/user.rs

use sqlx::MySqlPool;

#[derive(sqlx::FromRow, Debug)]
pub struct DbUser {
    pub id: i64,
    pub username: String,
    pub password: String,
    pub role: String,
}

pub async fn find_user_by_username(
    pool: &amp;amp;MySqlPool,
    username: &amp;amp;str
) -&amp;gt; Result&amp;lt;Option&amp;lt;DbUser&amp;gt;, sqlx::Error&amp;gt; {
    let user = sqlx::query_as::&amp;lt;_, DbUser&amp;gt;(
        "SELECT id, username, password, role FROM users WHERE username = ? LIMIT 1"
    )
    .bind(username)
    .fetch_optional(pool)
    .await?;

    Ok(user)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;7) &lt;strong&gt;Step 5: Make rate limiting stricter only for login (best practice)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Instead of limiting every route equally, you usually want:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/login: 5 requests / minute

/uploads: 10 requests / minute

/home/vehicles: higher limit (like 120/min)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Simple way: apply middleware to a specific scope&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.service(
    web::scope("/api")
        // Public routes
        .route("/home/vehicles", web::get().to(handlers::list_home_vehicle_cards_handler))
        // Login scope rate limited stricter
        .service(
            web::scope("")
                .wrap(RateLimitMiddleware::new(RateLimiter::new(60, 5)))
                .route("/login", web::post().to(handlers::login))
        )
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This keeps your site usable while protecting sensitive endpoints.&lt;/p&gt;

&lt;p&gt;8) &lt;strong&gt;Production notes (very important)&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;In-memory limiter limitations&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Works per server instance only.&lt;/p&gt;

&lt;p&gt;If you run 3 servers, each has its own counters (rate limiting becomes weaker).&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Production upgrade&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Replace HashMap with Redis counter (shared store).

Same “key/window/count” logic, but stored in Redis.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Practical Example
&lt;/h2&gt;

&lt;p&gt;=================env===============&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;API_RATE_LIMIT_PER_MINUTE=120
LOGIN_RATE_LIMIT_PER_MINUTE=10
CRUD_WRITE_RATE_LIMIT_PER_MINUTE=40
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;=========config.rs=====================&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   pub api_rate_limit_per_minute: u32,
    pub login_rate_limit_per_minute: u32,
    pub crud_write_rate_limit_per_minute: u32,
impl AppConfig {
    pub fn from_env() -&amp;gt; Self {
 let api_rate_limit_per_minute = env::var("API_RATE_LIMIT_PER_MINUTE")
            .ok()
            .and_then(|v| v.parse::&amp;lt;u32&amp;gt;().ok())
            .filter(|v| *v &amp;gt; 0)
            .unwrap_or(120);
        let login_rate_limit_per_minute = env::var("LOGIN_RATE_LIMIT_PER_MINUTE")
            .ok()
            .and_then(|v| v.parse::&amp;lt;u32&amp;gt;().ok())
            .filter(|v| *v &amp;gt; 0)
            .unwrap_or(10);
        let crud_write_rate_limit_per_minute = env::var("CRUD_WRITE_RATE_LIMIT_PER_MINUTE")
            .ok()
            .and_then(|v| v.parse::&amp;lt;u32&amp;gt;().ok())
            .filter(|v| *v &amp;gt; 0)
            .unwrap_or(40);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;==================main.rs=======================&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; .service(
                web::scope("/api")
                    .wrap(middleware::RateLimit::per_minute(cfg.api_rate_limit_per_minute))
                    .service(
                        web::scope("")
                            .wrap(middleware::RateLimit::per_minute(cfg.login_rate_limit_per_minute))
                            .route("/login", web::post().to(handlers::login)),
                    )
 .service(
       web::scope("")
       .wrap(middleware::require_roles(&amp;amp;["user"]))
       .wrap(middleware::RateLimit::mutations_per_minute(
        cfg.crud_write_rate_limit_per_minute,
       ))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;===========================mod.rs==================&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pub mod auth_middleware;
pub mod rate_limit_middleware;
pub mod role_middleware;

pub use auth_middleware::AuthMiddleware;
pub use rate_limit_middleware::RateLimit;
pub use role_middleware::require_roles;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;=================middleware=======================&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use std::collections::HashMap;
use std::future::{ready, Ready};
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use actix_web::{
    body::{EitherBody, MessageBody},
    dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
    http::header::{HeaderValue, RETRY_AFTER},
    http::Method,
    Error, HttpResponse,
};
use futures_util::future::LocalBoxFuture;
use serde_json::json;

#[derive(Clone)]
struct WindowState {
    count: u32,
    window_start: Instant,
}

#[derive(Clone)]
pub struct RateLimit {
    max_requests: u32,
    window: Duration,
    entries: Arc&amp;lt;Mutex&amp;lt;HashMap&amp;lt;String, WindowState&amp;gt;&amp;gt;&amp;gt;,
    mode: LimitMode,
}

#[derive(Clone, Copy)]
enum LimitMode {
    All,
    MutationsOnly,
}

impl RateLimit {
    pub fn per_minute(max_requests: u32) -&amp;gt; Self {
        Self {
            max_requests,
            window: Duration::from_secs(60),
            entries: Arc::new(Mutex::new(HashMap::new())),
            mode: LimitMode::All,
        }
    }

    pub fn mutations_per_minute(max_requests: u32) -&amp;gt; Self {
        Self {
            max_requests,
            window: Duration::from_secs(60),
            entries: Arc::new(Mutex::new(HashMap::new())),
            mode: LimitMode::MutationsOnly,
        }
    }

    fn client_key(req: &amp;amp;ServiceRequest) -&amp;gt; String {
        req.connection_info()
            .realip_remote_addr()
            .map(|s| s.to_string())
            .or_else(|| req.peer_addr().map(|a| a.ip().to_string()))
            .unwrap_or_else(|| "unknown".to_string())
    }

}

impl&amp;lt;S, B&amp;gt; Transform&amp;lt;S, ServiceRequest&amp;gt; for RateLimit
where
    S: Service&amp;lt;ServiceRequest, Response = ServiceResponse&amp;lt;B&amp;gt;, Error = Error&amp;gt; + 'static,
    B: MessageBody + 'static,
{
    type Response = ServiceResponse&amp;lt;EitherBody&amp;lt;B&amp;gt;&amp;gt;;
    type Error = Error;
    type InitError = ();
    type Transform = RateLimitService&amp;lt;S&amp;gt;;
    type Future = Ready&amp;lt;Result&amp;lt;Self::Transform, Self::InitError&amp;gt;&amp;gt;;

    fn new_transform(&amp;amp;self, service: S) -&amp;gt; Self::Future {
        ready(Ok(RateLimitService {
            service: Rc::new(service),
            max_requests: self.max_requests,
            window: self.window,
            entries: self.entries.clone(),
            mode: self.mode,
        }))
    }
}

pub struct RateLimitService&amp;lt;S&amp;gt; {
    service: Rc&amp;lt;S&amp;gt;,
    max_requests: u32,
    window: Duration,
    entries: Arc&amp;lt;Mutex&amp;lt;HashMap&amp;lt;String, WindowState&amp;gt;&amp;gt;&amp;gt;,
    mode: LimitMode,
}

impl&amp;lt;S, B&amp;gt; Service&amp;lt;ServiceRequest&amp;gt; for RateLimitService&amp;lt;S&amp;gt;
where
    S: Service&amp;lt;ServiceRequest, Response = ServiceResponse&amp;lt;B&amp;gt;, Error = Error&amp;gt; + 'static,
    B: MessageBody + 'static,
{
    type Response = ServiceResponse&amp;lt;EitherBody&amp;lt;B&amp;gt;&amp;gt;;
    type Error = Error;
    type Future = LocalBoxFuture&amp;lt;'static, Result&amp;lt;Self::Response, Self::Error&amp;gt;&amp;gt;;

    forward_ready!(service);

    fn call(&amp;amp;self, req: ServiceRequest) -&amp;gt; Self::Future {
        let service = self.service.clone();
        let max_requests = self.max_requests;
        let window = self.window;
        let entries = self.entries.clone();
        let mode = self.mode;

        Box::pin(async move {
            if matches!(mode, LimitMode::MutationsOnly)
                &amp;amp;&amp;amp; !matches!(
                    *req.method(),
                    Method::POST | Method::PUT | Method::PATCH | Method::DELETE
                )
            {
                let response = service.call(req).await?;
                return Ok(response.map_into_left_body());
            }

            let key = RateLimit::client_key(&amp;amp;req);
            let now = Instant::now();

            let mut retry_after_secs = 0u64;
            let allowed = {
                let mut map = entries.lock().expect("rate_limit mutex poisoned");

                // Opportunistic cleanup to keep memory bounded for inactive clients.
                map.retain(|_, state| now.duration_since(state.window_start) &amp;lt; window);

                let state = map.entry(key).or_insert(WindowState {
                    count: 0,
                    window_start: now,
                });

                if now.duration_since(state.window_start) &amp;gt;= window {
                    state.count = 0;
                    state.window_start = now;
                }

                if state.count &amp;gt;= max_requests {
                    retry_after_secs = window
                        .saturating_sub(now.duration_since(state.window_start))
                        .as_secs()
                        .max(1);
                    false
                } else {
                    state.count += 1;
                    true
                }
            };

            if !allowed {
                let mut response = HttpResponse::TooManyRequests().json(json!({
                    "message": "Too many requests. Please try again later."
                }));
                response
                    .headers_mut()
                    .insert(RETRY_AFTER, HeaderValue::from_str(&amp;amp;retry_after_secs.to_string()).unwrap_or_else(|_| HeaderValue::from_static("60")));

                return Ok(req.into_response(response).map_into_right_body());
            }

            let response = service.call(req).await?;
            Ok(response.map_into_left_body())
        })
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
  </channel>
</rss>
