<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tamrakar Shreyaa on Medium]]></title>
        <description><![CDATA[Stories by Tamrakar Shreyaa on Medium]]></description>
        <link>https://medium.com/@tamrakar-shreyaa?source=rss-e6cf9555e73c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Dih9HdxqZnLskT20</url>
            <title>Stories by Tamrakar Shreyaa on Medium</title>
            <link>https://medium.com/@tamrakar-shreyaa?source=rss-e6cf9555e73c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 02:52:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tamrakar-shreyaa/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From Website to Answers: A Technical Deep Dive into a NestJS RAG Chatbot]]></title>
            <link>https://tamrakar-shreyaa.medium.com/from-website-to-answers-a-technical-deep-dive-into-a-nestjs-rag-chatbot-71685f76d4f9?source=rss-e6cf9555e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/71685f76d4f9</guid>
            <category><![CDATA[ai-chatbot]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[software-engineer]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Tamrakar Shreyaa]]></dc:creator>
            <pubDate>Mon, 25 May 2026 03:14:26 GMT</pubDate>
            <atom:updated>2026-05-25T03:15:03.358Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TGasSZ4OTTzWBf99z2dxA.png" /></figure><p>If you have ever wanted to make your chatbot answer based on your own website content (instead of only general model knowledge).In this post, I’ll walk through the backend architecture of my RAG chatbot built with:</p><ul><li>NestJS (API framework)</li><li>OpenAI (embeddings + chat completion)</li><li>PostgreSQL + pgvector-style similarity search</li><li>TypeORM</li><li>Axios + Cheerio (web scraping)</li></ul><p>The goal is simple: ingest a website, store its semantic chunks, and answer questions grounded in that content.</p><h3>Why RAG on the Backend?</h3><p>A standard chatbot can produce generic responses. With Retrieval-Augmented Generation (RAG), the backend first retrieves relevant content from your own data, then asks the LLM to answer using that context.</p><p>That gives you a better balance of:</p><ul><li>grounded answers from your website content</li><li>general reasoning from the model when context is partial</li></ul><h3><strong>How Does RAG Work? (Simple Explanation)</strong></h3><pre>User gives a Website URL<br>        ↓<br>Scraper reads all text from the website<br>        ↓<br>Text is split into small chunks (500 chars each)<br>        ↓<br>Each chunk is converted to a vector (numbers) using OpenAI Embeddings<br>        ↓<br>Vectors are stored in PostgreSQL (pgvector)<br>        ↓<br>User asks a question<br>        ↓<br>Question is also converted to a vector<br>        ↓<br>System finds the most similar chunks from the database<br>        ↓<br>Similar chunks + Question are sent to OpenAI GPT<br>        ↓<br>GPT generates a human-friendly answer<br>        ↓<br>Answer is returned to the user</pre><h3><strong>Why Not Just Send the Whole Website to GPT?</strong></h3><ul><li>Websites can have thousands of words — too large for AI</li><li>RAG finds only the <strong>relevant parts</strong> and sends those</li><li>Faster, cheaper, and more accurate</li></ul><h3>Core backend components</h3><ul><li>ChatController for API endpoints</li></ul><pre>import { Controller, Post, Body, Delete, BadRequestException } from &#39;@nestjs/common&#39;;<br>import { ChatService } from &#39;./chat.service&#39;;<br>import { ScraperService } from &#39;../scraper/scraper.service&#39;;<br>import { EmbeddingsService } from &#39;../embeddings/embeddings.service&#39;;<br><br>@Controller(&#39;chat&#39;)<br>// POST /chat/ingest — scrape and store a website.<br>// POST /chat/ask — ask a question.<br>// DELETE /chat/clear — remove stored data for a URL.<br>export class ChatController {<br>    constructor(<br>        private chatService: ChatService,<br>        private scraperService: ScraperService,<br>        private embeddingsService: EmbeddingsService,<br>    ) { }<br><br>    // Step 1: Scrape &amp; ingest a website<br>    @Post(&#39;ingest&#39;)<br>    async ingest(@Body(&#39;url&#39;) url: string) {<br>        url = this.validateAndNormalizeUrl(url);<br>        await this.embeddingsService.clearByUrl(url); // avoid duplicates<br>        const chunks = await this.scraperService.scrapeWebsite(url);<br>        await this.embeddingsService.storeChunks(chunks, url);<br>        return { message: ` Ingested ${chunks.length} chunks from ${url}` };<br>    }<br><br>    // Step 2: Ask a question<br>    @Post(&#39;ask&#39;)<br>    async ask(@Body(&#39;question&#39;) question: string) {<br>        const result = await this.chatService.chat(question);<br>        return result;<br>    }<br><br>    // Optional: Clear all data for a URL<br>    @Delete(&#39;clear&#39;)<br>    async clear(@Body(&#39;url&#39;) url: string) {<br>        await this.embeddingsService.clearByUrl(url);<br>        return { message: ` Cleared embeddings for ${url}` };<br>    }<br><br>    private validateAndNormalizeUrl(url: string): string {<br>        if (!url || typeof url !== &#39;string&#39;) {<br>            throw new BadRequestException(&#39;url is required&#39;);<br>        }<br><br>        const trimmed = url.trim();<br>        if (trimmed.includes(&#39;,&#39;)) {<br>            throw new BadRequestException(<br>                &#39;Please provide only one URL. Comma-separated URLs are not supported.&#39;,<br>            );<br>        }<br><br>        try {<br>            const parsed = new URL(trimmed);<br>            if (![&#39;http:&#39;, &#39;https:&#39;].includes(parsed.protocol)) {<br>                throw new BadRequestException(&#39;URL must start with http:// or https://&#39;);<br>            }<br>            return parsed.toString();<br>        } catch {<br>            throw new BadRequestException(&#39;Invalid URL format&#39;);<br>        }<br>    }<br>}</pre><ul><li>ScraperService for extraction and chunking</li></ul><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import axios from &#39;axios&#39;;<br>import * as cheerio from &#39;cheerio&#39;;<br><br>@Injectable()<br>export class ScraperService {<br>  // Takes a website URL.<br>  // Downloads the HTML using Axios.<br>  // Parses and cleans text using Cheerio (removes scripts, nav, footer).<br>  // Splits text into chunks of ~500 characters with 50 char overlap.<br>  async scrapeWebsite(url: string): Promise&lt;string[]&gt; {<br>    const { data } = await axios.get(url);<br>    const $ = cheerio.load(data);<br><br>    // Remove noise<br>    $(&#39;script, style, nav, footer, header, iframe&#39;).remove();<br><br>    const text = $(&#39;body&#39;).text();<br>    const cleaned = text.replace(/\s+/g, &#39; &#39;).trim();<br><br>    if (!cleaned) {<br>      throw new Error(&#39;Scraped page has no readable text content.&#39;);<br>    }<br><br>    // Chunk into ~500 char pieces with overlap<br>    return this.chunkText(cleaned, 500, 50);<br>  }<br><br>  private chunkText(text: string, size: number, overlap: number): string[] {<br>    const chunks: string[] = [];<br>    let i = 0;<br>    while (i &lt; text.length) {<br>      chunks.push(text.slice(i, i + size));<br>      i += size - overlap; // overlap for context continuity<br>    }<br>    return chunks;<br>  }<br>}</pre><ul><li>EmbeddingsService for vector generation + retrieval</li></ul><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { InjectRepository } from &#39;@nestjs/typeorm&#39;;<br>import { Repository, DataSource } from &#39;typeorm&#39;;<br>import OpenAI from &#39;openai&#39;;<br>import { EmbeddingEntity } from &#39;./embedding.entity&#39;;<br><br>export type RetrievedChunk = {<br>  content: string;<br>  sourceUrl: string;<br>  distance: number;<br>};<br><br>@Injectable()<br>export class EmbeddingsService {<br>  private openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });<br><br>  constructor(<br>    @InjectRepository(EmbeddingEntity)<br>    private embeddingRepo: Repository&lt;EmbeddingEntity&gt;,<br>    private dataSource: DataSource,<br>  ) {}<br><br>  // Embed and store all chunks<br>  async storeChunks(chunks: string[], sourceUrl: string): Promise&lt;void&gt; {<br>    for (const chunk of chunks) {<br>      const embedding = await this.embed(chunk);<br><br>      const entity = this.embeddingRepo.create({<br>        content: chunk,<br>        sourceUrl,<br>        embedding,<br>      });<br><br>      await this.embeddingRepo.save(entity);<br>    }<br>  }<br><br>  // Find similar chunks and filter weak matches by distance threshold<br>  async findRelevantChunks(<br>    question: string,<br>    topK = 5,<br>    maxDistance = 0.65,<br>  ): Promise&lt;RetrievedChunk[]&gt; {<br>    const queryEmbedding = await this.embed(question);<br>    const vectorString = `[${queryEmbedding.join(&#39;,&#39;)}]`;<br><br>    // Use pgvector cosine distance operator &lt;=&gt;<br>    const results = await this.dataSource.query(<br>      `SELECT content, &quot;sourceUrl&quot;, (embedding::vector &lt;=&gt; $1::vector) AS distance<br>       FROM embeddings<br>       ORDER BY embedding::vector &lt;=&gt; $1::vector<br>       LIMIT $2`,<br>      [vectorString, topK],<br>    );<br><br>    return results<br>      .filter((r: any) =&gt; Number(r.distance) &lt;= maxDistance)<br>      .map((r: any) =&gt; ({<br>        content: r.content,<br>        sourceUrl: r.sourceUrl,<br>        distance: Number(r.distance),<br>      }));<br>  }<br><br>  // Clear all embeddings for a URL (re-ingest)<br>  async clearByUrl(sourceUrl: string): Promise&lt;void&gt; {<br>    await this.embeddingRepo.delete({ sourceUrl });<br>  }<br><br>  private async embed(text: string): Promise&lt;number[]&gt; {<br>    const res = await this.openai.embeddings.create({<br>      model: &#39;text-embedding-3-small&#39;,<br>      input: text,<br>    });<br>    return res.data[0].embedding;<br>  }<br>}</pre><ul><li>ChatService for orchestration and prompt strategy</li></ul><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import OpenAI from &#39;openai&#39;;<br>import { EmbeddingsService } from &#39;../embeddings/embeddings.service&#39;;<br><br>type ChatResult = {<br>  answer: string;<br>  sources: string[];<br>  usedContext: boolean;<br>};<br><br>@Injectable()<br>export class ChatService {<br>  private openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });<br><br>  constructor(private embeddingsService: EmbeddingsService) {}<br><br>  // Takes user&#39;s question.<br>  // Finds relevant chunks from the database.<br>  // Sends chunks + question to OpenAI GPT.<br>  // Returns the answer.<br>  async chat(question: string): Promise&lt;ChatResult&gt; {<br>    // 1. Find relevant chunks from pgvector<br>    const relevantChunks = await this.embeddingsService.findRelevantChunks(<br>      question,<br>    );<br><br>    if (!relevantChunks.length) {<br>      return {<br>        answer: &quot;I don&#39;t have that information.&quot;,<br>        sources: [],<br>        usedContext: false,<br>      };<br>    }<br><br>    const context = relevantChunks.map((chunk) =&gt; chunk.content).join(&#39;\n\n&#39;);<br>    const sources = [...new Set(relevantChunks.map((chunk) =&gt; chunk.sourceUrl))];<br><br>    // 2. Send to OpenAI GPT<br>    const response = await this.openai.chat.completions.create({<br>      model: &#39;gpt-4o-mini&#39;,<br>      messages: [<br>        {<br>          role: &#39;system&#39;,<br>          content:<br>            &#39;You are a helpful assistant. Use provided website content as the primary source. If context is partial, first share what is known from context, then clearly label &quot;General guidance&quot; for broader advice. Never invent specific website facts that are not supported by context.&#39;,<br>        },<br>        {<br>          role: &#39;user&#39;,<br>          content: `Website Content:\n${context}\n\nQuestion: ${question}`,<br>        },<br>      ],<br>    });<br><br>    return {<br>      answer: response.choices[0].message.content ?? &#39;Unable to generate an answer.&#39;,<br>      sources,<br>      usedContext: true,<br>    };<br>  }<br>}</pre><ul><li>EmbeddingEntity for persistence</li></ul><pre>import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn } from &#39;typeorm&#39;;<br><br>@Entity(&#39;embeddings&#39;)<br>// Defines the database table embeddings.<br>// Stores: chunk text, source URL, and the vector (array of numbers).<br>export class EmbeddingEntity {<br>  @PrimaryGeneratedColumn()<br>  id: number;<br><br>  @Column(&#39;text&#39;)<br>  content: string;          // Original chunk text<br><br>  @Column(&#39;text&#39;)<br>  sourceUrl: string;        // Where it came from<br><br>  @Column(&#39;float8&#39;, { array: true })<br>  embedding: number[];      // Vector stored as float array<br><br>  @CreateDateColumn()<br>  createdAt: Date;<br>}</pre><h3>Environment Variables</h3><pre># OpenAI API Key (used for both embeddings and chat)<br>OPENAI_API_KEY=sk-proj-xxxxxxxxxxxxxxxx<br><br># PostgreSQL Database<br>DB_HOST=localhost<br>DB_PORT=5432<br>DB_USER=xxxxxxxxxxxxx<br>DB_PASS=xxxxxxxxxxxx<br>DB_NAME=xxxxxxxxxxxx</pre><h3>API Endpoints</h3><h4>1. Ingest a Website</h4><p><strong>Scrapes the website and stores its content in the database</strong></p><pre>POST http://localhost:3000/chat/ingest<br>Content-Type: application/json<br><br>{<br>  &quot;url&quot;: &quot;https://example.com&quot;<br>}<br><br>Response:<br><br>{<br>  &quot;message&quot;: &quot;Ingested 42 chunks from https://example.com&quot;<br>}</pre><h4>2. Ask a Question</h4><p><strong>Finds relevant content and generates an answer</strong></p><pre>POST http://localhost:3000/chat/ask<br>Content-Type: application/json<br><br>{<br>  &quot;question&quot;: &quot;What services do you offer?&quot;<br>}<br><br>Response:<br>{<br>  &quot;answer&quot;: &quot;Based on the website, they offer...&quot;<br>}</pre><h4>3. Clear Website Data (Optional)</h4><p><strong>Removes all stored chunks for a specific URL</strong></p><pre>DELETE http://localhost:3000/chat/clear<br>Content-Type: application/json<br><br>{<br>  &quot;url&quot;: &quot;https://example.com&quot;<br>}<br><br>Response:<br><br>{<br>  &quot;message&quot;: &quot;Cleared embeddings for https://example.com&quot;<br>}</pre><p>🔗 <a href="https://github.com/tamracar/rag-chatbot"><strong>GitHub Repo</strong></a></p><ul><li><a href="https://tamrakar-shreyaa.medium.com/prompt-engineering-the-complete-beginners-guide-to-talking-to-ai-with-real-examples-c5b00d71d604">Prompt Engineering: The Complete Beginner’s Guide to Talking to AI (With Real Examples)</a></li><li><a href="https://tamrakar-shreyaa.medium.com/why-ux-and-cx-should-be-top-priorities-in-hotel-ota-platforms-40a838ac5e5e">Why UX and CX Should Be Top Priorities in Hotel OTA Platforms</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71685f76d4f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Engineering: The Complete Beginner’s Guide to Talking to AI (With Real Examples)]]></title>
            <link>https://tamrakar-shreyaa.medium.com/prompt-engineering-the-complete-beginners-guide-to-talking-to-ai-with-real-examples-c5b00d71d604?source=rss-e6cf9555e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5b00d71d604</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[beginner]]></category>
            <dc:creator><![CDATA[Tamrakar Shreyaa]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 13:16:01 GMT</pubDate>
            <atom:updated>2026-04-10T13:16:01.372Z</atom:updated>
            <content:encoded><![CDATA[<p>Everything you need to know — from what a prompt actually is, to techniques that make AI dramatically more useful.</p><p>Most people use AI like a search engine. They type a vague question, get a mediocre answer, and assume the AI “isn’t that smart.” But the problem isn’t the AI — it’s the prompt. Prompt engineering is the skill of writing instructions that get you exactly what you want from an AI model. It’s not coding. It’s not magic. It’s communication — but more precise than you’re used to. In this guide, I’ll walk you through 14 core techniques, from the basics to the ones professional AI engineers use every day. Every technique has a plain-English explanation and a real example you can copy and try right now.</p><h3><strong>What Is Prompt Engineering?</strong></h3><p>A **prompt** is the text you send to an AI. **Prompt engineering** is the skill of writing that text in the best possible way. Think of an AI like an extremely capable employee who follows instructions very literally. A vague instruction gets a vague result. A specific, well-structured instruction gets an excellent one. Prompt engineers do four things: — Design prompts for AI products and chatbots — Test and improve prompts through experimentation — Build workflows that chain multiple AI calls together — Measure output quality and consistency over time You don’t need to be a developer. Anyone who uses AI regularly can learn this.</p><h3><strong>How the AI Actually Reads Your Words (Transformer Architecture)</strong></h3><p>Before learning techniques, it helps to know *why* they work. When you type a message, the AI doesn’t read it word by word. It reads everything at once, and every word “looks at” every other word to understand meaning. The word “it” figures out what it refers to by checking which nearby word makes the most sense.</p><p>The practical rule: Be specific with nouns. Vague words like “it,” “this,” or “that” force the AI to guess — and it often guesses wrong.</p><ul><li><strong>Bad:</strong> Fix it so it works.</li><li><strong>Good:</strong> Fix the login button so it submits the form correctly.One sentence change. Completely different result.</li></ul><h3><strong>The Creativity Dial: Temperature and Top-p</strong></h3><p>Temperature controls how random or creative the AI’s word choices are.</p><p>— <strong>Low temperature (0–0.2):</strong>Safe, predictable, accurate. Best for facts, math, and code.</p><p>— <strong>High temperature (0.7–1.0):</strong> Creative, varied, surprising. Best for writing, brainstorming, and ideas.</p><p><strong>Example</strong> — same prompt, different temperature:</p><p>Write a tagline for a coffee shop.</p><p>— <strong>Temperature 0.1</strong> → Great coffee, every time.</p><p>— <strong>Temperature 0.8</strong> → Where mornings taste like possibility.</p><p>— <strong>Temperature 1.5</strong> → Sip the velvet thunder of bean dreams. (too random)</p><ul><li><strong>Rule</strong>: Use low temperature when there’s a right or wrong answer. Use higher when creativity is the goal.</li></ul><h3><strong>Standard Prompt (no examples, direct ask)</strong></h3><p>Just ask directly. Works for common tasks. Always specify your desired format. <strong>Example</strong>:Explain what a database is in 2 sentences, using a simple analogy, for someone who has never coded.</p><h3>Zero-Shot Prompt (no examples, with a role)</h3><p>Describe the task without any demonstration. Add a role to improve quality instantly. <strong>Example</strong>:You are a customer service analyst. Classify this review as POSITIVE or NEGATIVE: The package arrived damaged.</p><h3>One-Shot Prompt (one example to anchor format)</h3><p>Show one example of exactly what you want. The AI copies its structure precisely.</p><p><strong>Example:</strong></p><ul><li><strong>Input</strong>: Dog → Output: A dog is a loyal pet known for its friendship with humans.</li></ul><p>Now do the same for: Cat</p><ul><li><strong>Output</strong>: A cat is an independent pet known for its curious and graceful nature.</li></ul><h3>Few-Shot Prompt (2–5 examples to teach a pattern)</h3><p>Multiple examples teach the AI a pattern it can apply to new inputs — no training required.</p><p><strong>Example</strong>: teaching a 4-category sentiment system:</p><p>— I love this! → HAPPY</p><p>— This is broken. → ANGRY</p><p>— Arrived on time. → NEUTRAL</p><p>— Still waiting after 3 weeks!→ FRUSTRATED</p><p>Now classify: “Finally got it working, what a relief.”</p><p>Output: HAPPY</p><h3>Where You Put Things Matters: Context Placement</h3><p>Research shows that AI pays most attention to content at the start and end of a prompt. Anything buried in the long middle of a large prompt receives less attention — this is called the “lost in the middle” problem.</p><p>The fix: Put critical instructions at both the top and the bottom. Never bury your most important rules in the middle.</p><p><strong>Wrong layout:</strong></p><p>``` You are a helpful assistant.</p><p>[long background…]</p><p>[more context…]</p><p>Always answer in simple English. ← buried, may be ignored</p><p>[more info…]</p><p>Now answer: … ```</p><p><strong>Right layout:</strong></p><p>``` [TOP] You are a helpful assistant. Always answer in simple English.</p><p>[MIDDLE] Background info and context</p><p>[BOTTOM] Remember: answer in simple English. Now answer: … ```</p><p><strong>Same content</strong>. Totally different result.</p><h3>Ask the AI to Think Out Loud: Chain-of-Thought</h3><p>Adding “think step by step” to a prompt is one of the single most effective improvements you can make — especially for math, logic, or multi-step tasks.</p><p>Each reasoning step the AI writes becomes part of its thinking, making the next step more accurate.</p><p><strong>**Without CoT:*</strong>*If I buy 3 notebooks at $4 each with a 20% discount, what do I pay?</p><p><strong>Output:</strong> “$9.60” — correct, but you can’t verify it.</p><p><strong>**With CoT (“think step by step”):**</strong></p><p>— Step 1: 3 × $4 = $12 total</p><p>— Step 2: 20% discount = $12 × 0.20 = $2.40 saved</p><p>— Step 3: Final price = $12 − $2.40 = $9.60</p><p>Now you can check every step. Errors become visible and fixable.</p><h3>Get Machine-Readable Answers: Structured Output</h3><p>When you need to use the AI’s answer in a spreadsheet, app, or code, you need structured output — JSON, a table, a numbered list, or any other specific format.</p><p><strong>Free-form (hard to use)</strong>:Tell me about this product.</p><p><strong>Output:</strong> The Red Notebook is a great product priced at $12. It has 200 pages and is red…</p><p><strong>Structured (easy to use)</strong>: Return ONLY JSON with no other text: {name, price, pages, color}</p><p><strong>Output:</strong></p><p>```json</p><p>{</p><p>“name”: “Red Notebook”,</p><p>“price”: 12,</p><p>“pages”: 200,</p><p>“color”: “red”</p><p>} ```</p><p>Always add “return ONLY [format], no other text” — without this, the AI often wraps the answer in extra sentences that break parsing.</p><h3>Future-Proofing Prompts</h3><p>AI models are updated regularly. Prompts that rely on current quirks break after updates. Write prompts that describe the output explicitly rather than relying on default behavior.</p><ul><li><strong>Fragile:</strong> Don’t use bullet points.</li><li><strong>Robust:</strong> Write your answer as exactly 2 plain paragraphs. No bullet points, no headers, no bold text.</li></ul><h3>Emotional Prompts</h3><p>AI models learned from human conversations. When humans consider something high-stakes, they take it more seriously — and the AI does too.</p><ul><li><strong>Casual: </strong>Check this email for errors.</li><li><strong>With stakes:</strong>Please review this email very carefully. It goes to our biggest client and one mistake could damage the relationship. Check grammar, tone, professionalism, and clarity.</li></ul><p>The second prompt produces a dramatically deeper review.</p><h3>Delimiters for Complex Prompts</h3><p>When your prompt mixes instructions with content (like pasting a document to summarize), use XML tags or triple quotes to separate them clearly. This prevents the AI from confusing content as instructions — and protects against prompt injection.</p><p>``` Summarize the text below in 3 bullet points. [Your document text here] ```</p><h3>Personas</h3><p>Assigning a role changes what knowledge the AI focuses on — not just the tone.</p><p><strong>Same question:</strong> Should I use a password or PIN?</p><p>— No persona → Generic pros and cons</p><p>— You are a friendly teacher for beginners → Simple analogy about secret words</p><p>— You are a cybersecurity expert → Entropy analysis and threat model discussion</p><p><strong>Formula:</strong>You are a [seniority] [role] who always [specific behavior].</p><h3>Final Thoughts</h3><p>Prompt engineering isn’t a mysterious skill reserved for AI researchers. It’s clear communication — applied to a very literal, very capable listener.</p><p>The most impactful changes you can make today:</p><ol><li>Add “think step by step” to any multi-step question</li></ol><p>2. Always specify the format and length you want</p><p>3. Assign a role at the start: “You are a [role]…”</p><p>4. Put your most important instruction at the top *and* the bottom</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5b00d71d604" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why UX and CX Should Be Top Priorities in Hotel OTA Platforms]]></title>
            <link>https://tamrakar-shreyaa.medium.com/why-ux-and-cx-should-be-top-priorities-in-hotel-ota-platforms-40a838ac5e5e?source=rss-e6cf9555e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/40a838ac5e5e</guid>
            <category><![CDATA[hospitality-industry]]></category>
            <category><![CDATA[cx]]></category>
            <category><![CDATA[ux-research]]></category>
            <category><![CDATA[nepal-hotels]]></category>
            <category><![CDATA[hotel-booking]]></category>
            <dc:creator><![CDATA[Tamrakar Shreyaa]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 04:17:53 GMT</pubDate>
            <atom:updated>2025-10-08T04:17:53.938Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eOyqLKCWUbAh7gb5UTP7Ow.png" /></figure><p><strong>In hotel tech, it’s not the code or the colors — it’s the customer journey that defines success.</strong><br>A great system architecture or a beautifully designed homepage means little if your users can’t easily find what they’re looking for. In the Hotel OTA world, where users expect instant results and effortless bookings, <strong>User Experience (UX)</strong> and <strong>Customer Experience (CX)</strong> are not optional — they’re everything.</p><p><strong>1. First Impressions Are Built on UX, Not Flash</strong></p><p>A stunning homepage or a fancy animation might impress at first , but users don’t come to a hotel booking site to admire design — they come to <strong>book rooms quickly and confidently</strong>.If your site looks amazing but users can’t find the “Book Now” button or get confused mid-way, they’ll leave — no matter how beautiful it is.</p><p><strong>A perfect image or animation doesn’t guarantee a customer — a smooth experience does.</strong></p><p><strong>2. The Real Business Impact Lies in CX</strong></p><p><strong>CX goes beyond visuals.</strong> It’s the emotional journey a user takes from the moment they land on your site until they receive their booking confirmation — and beyond.A positive CX means:</p><ul><li>Bookings happen faster</li><li>Users trust your brand more</li><li>They come back — and bring others</li></ul><p>In a competitive OTA market, where every click counts, <strong>CX directly translates into revenue</strong>.</p><p><strong>3.Every Department Has Its Own Lens — But UX/CX Connect Them All</strong></p><ul><li><strong>Branding Team:</strong> Wants impact. UX ensures that branding feels natural, not forced.</li><li><strong>Developers:</strong> Focus on system performance. UX ensures that power is delivered seamlessly to the user.</li><li><strong>Clients/Admins:</strong> Want easy control. CX ensures that managing listings, offers, and hotel data is intuitive.</li></ul><p>When each team works toward improving UX and CX, everyone wins — especially the end user.</p><p><strong>4. Simplify, Don’t Complicate</strong></p><p>Many OTAs fall into the trap of “more features, more visuals.” But the truth is, <strong>simplicity converts</strong>.Users shouldn’t have to think twice about:</p><ul><li>Where to search for a hotel</li><li>How to compare prices</li><li>Which button to click next</li></ul><p>A well-structured UX removes friction, builds trust, and gets users from <strong>search → selection → booking → confirmation</strong> effortlessly.</p><p>In a Hotel OTA platform, it’s not about perfect visuals or heavy animations — it’s about clarity, speed, trust, and ease.So while every department brings its strengths, <strong>UX and CX should always sit at the top of your product priorities</strong>.They’re not just design choices — they’re <strong>business strategies</strong> that turn browsers into bookers, and users into loyal customers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40a838ac5e5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nepali Text-to-Speech Engine from Scratch (No APIs Needed!)]]></title>
            <link>https://tamrakar-shreyaa.medium.com/nepali-text-to-speech-engine-from-scratch-no-apis-needed-f50f0550336d?source=rss-e6cf9555e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f50f0550336d</guid>
            <category><![CDATA[espeak-ng]]></category>
            <category><![CDATA[no-third-party-api]]></category>
            <category><![CDATA[nestjs-docker]]></category>
            <category><![CDATA[text-to-speech]]></category>
            <category><![CDATA[nepali-tts]]></category>
            <dc:creator><![CDATA[Tamrakar Shreyaa]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 03:46:35 GMT</pubDate>
            <atom:updated>2025-04-23T03:46:35.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uV_V-5gQFOMf9dhzJZpqIw.jpeg" /></figure><p><em>“Imagine typing नमस्ते and instantly hearing it spoken by your own app — no Google or Amazon APIs required.”</em></p><p>Have you ever wanted to build a <strong>Nepali Text-to-Speech (TTS)</strong> system without relying on third-party APIs like Google or Amazon? Commercial TTS services can be expensive, restrictive, or lack good Nepali language support.In this article, I’ll walk you through how I built <strong>Nepali TTS engine</strong> using:</p><ul><li><strong>NestJS</strong> (Backend API)</li><li><strong>eSpeak-ng</strong> (Open-source TTS engine)</li><li><strong>Docker</strong> (For easy deployment)</li><li><strong>Simple HTML/JS Frontend</strong> (For demo)</li></ul><p>Let’s get started!</p><p><strong>Step 1: Setting Up the Backend (NestJS)</strong></p><p><strong>Install</strong> <strong>NestJs &amp; Dependencies</strong></p><pre>npm i -g @nestjs/cli<br>nest new nepali-tts<br>cd nepali-tts<br>npm install --save @nestjs/websockets @nestjs/platform-socket.io<br>npm install --save-dev @types/ws</pre><p><strong>Set Up the Text-to-Speech Service</strong></p><p>Create src/tts/tts.service.ts:</p><pre><br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { execSync } from &#39;child_process&#39;;<br>import { join } from &#39;path&#39;;<br>import { writeFileSync, unlinkSync, existsSync, mkdirSync } from &#39;fs&#39;;<br><br>@Injectable()<br>export class TtsService {<br>  private readonly outputDir = join(__dirname, &#39;../../output&#39;);<br><br>  constructor() {<br>    if (!existsSync(this.outputDir)) {<br>      mkdirSync(this.outputDir);<br>    }<br>  }<br><br>  async convertToSpeech(text: string): Promise&lt;string&gt; {<br>    // This is a simplified approach using eSpeak-ng (will be installed in Docker)<br>    // For Nepali, we&#39;ll use the Nepali language code &#39;ne&#39;<br>    <br>    const fileName = `tts_${Date.now()}.wav`;<br>    const filePath = join(this.outputDir, fileName);<br>    <br>    try {<br>      // Using eSpeak-ng for text-to-speech<br>      execSync(`espeak-ng -v ne &quot;${text}&quot; --stdout &gt; ${filePath}`);<br>      <br>      return filePath;<br>    } catch (error) {<br>      console.error(&#39;TTS conversion error:&#39;, error);<br>      throw new Error(&#39;Failed to convert text to speech&#39;);<br>    }<br>  }<br><br>  async deleteAudioFile(filePath: string): Promise&lt;void&gt; {<br>    try {<br>      if (existsSync(filePath)) {<br>        unlinkSync(filePath);<br>      }<br>    } catch (error) {<br>      console.error(&#39;Error deleting audio file:&#39;, error);<br>    }<br>  }<br>}</pre><p><strong>Add the API Endpoint</strong></p><p>Create src/tts/tts.controller.ts:</p><pre>import { Controller, Post, Body, Res, Get, Param, Delete } from &#39;@nestjs/common&#39;;<br>import { TtsService } from &#39;./tts.service&#39;;<br>import { Response } from &#39;express&#39;;<br>import { existsSync, createReadStream } from &#39;fs&#39;;<br>import { join } from &#39;path&#39;;<br><br>@Controller(&#39;tts&#39;)<br>export class TtsController {<br>  constructor(private readonly ttsService: TtsService) {}<br><br>  @Post()<br>  async convertToSpeech(@Body() body: { text: string }, @Res() res: Response) {<br>    try {<br>      const { text } = body;<br>      if (!text) {<br>        return res.status(400).json({ error: &#39;Text is required&#39; });<br>      }<br><br>      const filePath = await this.ttsService.convertToSpeech(text);<br>      const fileName = filePath.split(&#39;/&#39;).pop();<br><br>      return res.json({<br>        success: true,<br>        filePath: `/tts/audio/${fileName}`,<br>      });<br>    } catch (error) {<br>      return res.status(500).json({ error: error.message });<br>    }<br>  }<br><br>  @Get(&#39;audio/:filename&#39;)<br>  async getAudioFile(@Param(&#39;filename&#39;) filename: string, @Res() res: Response) {<br>    const filePath = join(__dirname, &#39;../../output&#39;, filename);<br>    <br>    if (!existsSync(filePath)) {<br>      return res.status(404).json({ error: &#39;File not found&#39; });<br>    }<br><br>    const fileStream = createReadStream(filePath);<br>    res.setHeader(&#39;Content-Type&#39;, &#39;audio/wav&#39;);<br>    fileStream.pipe(res);<br>  }<br><br>  @Delete(&#39;audio/:filename&#39;)<br>  async deleteAudioFile(@Param(&#39;filename&#39;) filename: string, @Res() res: Response) {<br>    const filePath = join(__dirname, &#39;../../output&#39;, filename);<br>    <br>    try {<br>      await this.ttsService.deleteAudioFile(filePath);<br>      return res.json({ success: true });<br>    } catch (error) {<br>      return res.status(500).json({ error: error.message });<br>    }<br>  }<br>}</pre><p><strong>Step 2: Dockerizing the Application</strong></p><p><strong>Dockerfile</strong></p><p>Create a Dockerfile in the root directory:</p><pre># Stage 1: Build the application<br>FROM node:18-alpine AS builder<br><br>WORKDIR /app<br><br>COPY package*.json ./<br>RUN npm install<br><br>COPY . .<br>RUN npm run build<br><br># Stage 2: Production image<br>FROM node:18-alpine<br><br>WORKDIR /app<br><br># Install eSpeak-ng for text-to-speech<br>RUN apk add --no-cache espeak-ng ffmpeg<br><br>COPY --from=builder /app/node_modules ./node_modules<br>COPY --from=builder /app/dist ./dist<br>COPY --from=builder /app/package*.json ./<br><br># Create output directory<br>RUN mkdir -p /app/output<br><br>EXPOSE 3000<br><br>CMD [&quot;npm&quot;, &quot;run&quot;, &quot;start:prod&quot;]<br></pre><p><strong>docker-compose.yml</strong></p><p>Create a docker-compose.yml in the root directory:</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  nepalitts:<br>    build: .<br>    ports:<br>      - &quot;3000:3000&quot;<br>    volumes:<br>      - ./output:/app/output<br>        - ./public:/app/public  # Add this line<br>      - ./src:/app/src       # For development<br>    environment:<br>      - NODE_ENV=production<br>    restart: unless-stopped</pre><p><strong>Step 3: Update NestJS Configuration</strong></p><p>Edit src/main.ts to ensure the server listens on all interfaces:</p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>import { join } from &#39;path&#39;;<br>import { NestExpressApplication } from &#39;@nestjs/platform-express&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create&lt;NestExpressApplication&gt;(AppModule);<br>  <br>  // Serve static files from /public<br>  app.useStaticAssets(join(__dirname, &#39;..&#39;, &#39;public&#39;));<br>  app.setBaseViewsDir(join(__dirname, &#39;..&#39;, &#39;public&#39;));<br>  app.setViewEngine(&#39;html&#39;);  // Treat .html as templates<br><br>  await app.listen(3000, &#39;0.0.0.0&#39;);<br><br>  app.enableCors({<br>    origin: &#39;*&#39;  // Allow all origins (for development)<br>  });<br>}<br>bootstrap();</pre><p><strong>Step 4: Create a simple frontend (HTML/LS)</strong></p><p>Add a public folder in your NestJS project and create index.html:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Nepali TTS Demo&lt;/title&gt;<br>    &lt;style&gt;<br>        body {<br>            font-family: Arial, sans-serif;<br>            max-width: 800px;<br>            margin: 0 auto;<br>            padding: 20px;<br>        }<br>        textarea {<br>            width: 100%;<br>            height: 100px;<br>            margin-bottom: 10px;<br>            font-size: 16px;<br>        }<br>        button {<br>            padding: 10px 15px;<br>            background-color: #4CAF50;<br>            color: white;<br>            border: none;<br>            cursor: pointer;<br>        }<br>        #audioPlayer {<br>            margin-top: 20px;<br>            width: 100%;<br>        }<br>        .loading {<br>            display: none;<br>            color: #666;<br>        }<br>    &lt;/style&gt;<br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/nepali-keyboard@1.0.0/dist/nepali-keyboard.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.jsdelivr.net/npm/nepali-keyboard@1.0.0/dist/nepali-keyboard.min.css&quot;&gt;<br>    <br>    &lt;div id=&quot;keyboard&quot;&gt;&lt;/div&gt;<br>    &lt;script&gt;<br>        document.addEventListener(&#39;DOMContentLoaded&#39;, function() {<br>            new NepaliKeyboard(document.getElementById(&#39;nepaliText&#39;), {<br>                theme: &#39;light&#39;,<br>                width: &#39;100%&#39;,<br>                height: &#39;200px&#39;<br>            });<br>        });<br>    &lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Nepali Text-to-Speech Demo&lt;/h1&gt;<br>    &lt;textarea id=&quot;nepaliText&quot; placeholder=&quot;नेपाली टेक्स्ट यहाँ टाइप गर्नुहोस्...&quot;&gt;&lt;/textarea&gt;<br>    &lt;button id=&quot;generateBtn&quot;&gt;Generate Speech&lt;/button&gt;<br>    &lt;div id=&quot;loading&quot; class=&quot;loading&quot;&gt;Generating audio...&lt;/div&gt;<br>    &lt;audio id=&quot;audioPlayer&quot; controls&gt;&lt;/audio&gt;<br><br>    &lt;script&gt;<br>        document.getElementById(&#39;generateBtn&#39;).addEventListener(&#39;click&#39;, async () =&gt; {<br>            const text = document.getElementById(&#39;nepaliText&#39;).value.trim();<br>            if (!text) {<br>                alert(&#39;कृपया नेपाली टेक्स्ट टाइप गर्नुहोस्&#39;);<br>                return;<br>            }<br><br>            const loading = document.getElementById(&#39;loading&#39;);<br>            const audioPlayer = document.getElementById(&#39;audioPlayer&#39;);<br>            <br>            loading.style.display = &#39;block&#39;;<br>            audioPlayer.style.display = &#39;none&#39;;<br><br>            try {<br>                // Call your NestJS API<br>                const response = await fetch(&#39;http://localhost:3000/tts&#39;, {<br>                    method: &#39;POST&#39;,<br>                    headers: {<br>                        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>                    },<br>                    body: JSON.stringify({ text })<br>                });<br><br>                const data = await response.json();<br>                <br>                if (data.success) {<br>                    // Directly play the audio<br>                    audioPlayer.src = data.filePath;<br>                    audioPlayer.style.display = &#39;block&#39;;<br>                    audioPlayer.play();<br>                } else {<br>                    throw new Error(data.error || &#39;Unknown error&#39;);<br>                }<br>            } catch (error) {<br>                console.error(&#39;Error:&#39;, error);<br>                alert(&#39;Audio generation failed: &#39; + error.message);<br>            } finally {<br>                loading.style.display = &#39;none&#39;;<br>            }<br>        });<br><br><br>     <br>audioPlayer.addEventListener(&#39;error&#39;, () =&gt; {<br>    alert(&#39;Audio playback failed. Please try again.&#39;);<br>    loading.style.display = &#39;none&#39;;<br>});<br><br>audioPlayer.addEventListener(&#39;canplay&#39;, () =&gt; {<br>    loading.style.display = &#39;none&#39;;<br>    audioPlayer.style.display = &#39;block&#39;;<br>});<br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>Step 5 : Build and Run</strong></p><pre>docker-compose down<br>docker-compose build<br>docker-compose up -d</pre><p><strong>Step 6 : Access the Web Demo</strong></p><p>Open your browser to:</p><pre>http://localhost:3000</pre><p>Type Nepali text (e.g., “सबैलाई नमस्ते”) and click <strong>Generate Speech</strong>.<br>The audio should play automatically!</p><p>🔗 <a href="https://github.com/tamracar/nepali-tts"><strong>GitHub Repo</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*6u8MQ0zQ78WdIR_w3x_O-g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f50f0550336d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Direct Booking in Nepal: Overcoming OTA Dominance and Driving Revenue]]></title>
            <link>https://tamrakar-shreyaa.medium.com/direct-booking-in-nepal-overcoming-ota-dominance-and-driving-revenue-89345a8748fd?source=rss-e6cf9555e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/89345a8748fd</guid>
            <category><![CDATA[hotel-industry]]></category>
            <category><![CDATA[increase-direct-booking]]></category>
            <category><![CDATA[nepal-hotels]]></category>
            <category><![CDATA[ota]]></category>
            <category><![CDATA[hotel-management]]></category>
            <dc:creator><![CDATA[Tamrakar Shreyaa]]></dc:creator>
            <pubDate>Wed, 15 Jan 2025 12:25:23 GMT</pubDate>
            <atom:updated>2025-01-15T12:25:23.066Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h4fT4LYGU7j8VHtUzCIRMQ.jpeg" /></figure><p>A <strong>Direct Booking Engine</strong> is an online tool integrated into a hotel’s website or mobile app that enables guests to make reservations directly with the hotel, without the need for third-party intermediaries like Online Travel Agencies (OTAs). It acts as a digital reservation system where potential guests can check room availability, compare rates, view room details, and confirm bookings in real-time.</p><p>Hotels in Nepal, especially higher-end and boutique establishments, are increasingly investing in user-friendly websites, booking engines, and digital marketing to encourage direct bookings. Offering incentives like discounts, free upgrades, or extra services for direct bookings is a common practice.</p><h3><strong>Key Features of a Direct Booking Engine</strong></h3><p><strong>Real-Time Availability and Pricing :</strong>It provides guests with real-time room availability and updated prices, eliminating the need to rely on external platforms for accurate information.</p><p><strong>User-Friendly Interface:</strong>A good booking engine offers a simple and intuitive interface, enabling users to search for rooms based on criteria like dates, number of guests, room type, and amenities.</p><p><strong>Secure Payment Processing :</strong>Direct booking engines support secure payment gateways, allowing guests to pay using various payment methods (credit cards, local payment providers, etc.) while ensuring data security.</p><p><strong>Personalization and Special Offers:</strong>Hotels can use booking engines to showcase personalized offers and exclusive promotions for direct bookings, such as discounts, free breakfast, or complimentary upgrades.</p><p><strong>Integration with Property Management System (PMS):</strong>The booking engine is often integrated with the hotel’s Property Management System (PMS) to automatically update room inventory, pricing, and reservations in real-time.</p><p><strong>Multi-Currency Support :</strong>To attract international travelers, the booking engine should support currencies, improving accessibility and convenience for diverse audiences.</p><p><strong>Upselling and Cross-Selling Capabilities:</strong>Many booking engines include features to suggest additional services (like airport transfers, spa packages, or dining options) during the booking process to increase revenue per guest.</p><p><strong>Room rate wise payment option :</strong>The booking engine allows guests to pay based on specific room rates and their associated policies, offering flexibility and transparency. For example, non-refundable rates may require full payment upfront, while refundable rates allow partial or deferred payments. This feature supports multiple payment methods, including credit cards, digital wallets, and local options, catering to diverse audiences. By providing dynamic payment plans like installments or full-payment discounts, hotels can enhance guest satisfaction, reduce booking abandonment, and increase revenue, while maintaining secure and seamless payment processing integrated with their Property Management System (PMS).</p><h3><strong>Why Hotels in Nepal Should Prioritize Direct Bookings</strong></h3><p>Hotels in Nepal, regardless of size or category, should consider focusing on increasing direct bookings for several compelling reasons:</p><p><strong>1. Increased Profit Margins :</strong>Direct bookings eliminate the commission fees charged by Online Travel Agencies (OTAs), which can range from 15% to 30%. By encouraging guests to book directly, hotels can retain a larger portion of the revenue. This is especially important for smaller and mid-range hotels operating on tight budgets, where reducing commission expenses can significantly impact profitability.</p><p><strong>2. Better Control Over Pricing and Inventory :</strong>By increasing direct bookings, hotels can gain greater control over their pricing strategy. Unlike OTAs, which often promote lower prices or run independent discounts, direct bookings give hotels the flexibility to offer personalized promotions, bundle services, and use dynamic pricing models. This control can help maintain rate parity and prevent revenue leakage.</p><p><strong>3. Increased Brand Awareness and Loyalty :</strong>Encouraging direct bookings enables hotels to promote their brand rather than relying on OTA branding. When guests book through the hotel’s official channels, they are more likely to remember the brand name, leading to better brand recall and customer loyalty. Moreover, direct channels allow hotels to introduce their own loyalty programs and exclusive offers to incentivize repeat bookings.</p><p><strong>4. Reduction of Overdependence on OTAs :</strong>While OTAs offer broad visibility and a vast customer base, relying solely on them exposes hotels to risks such as changes in commission structures, ranking algorithms, and contractual terms. Focusing on direct bookings helps hotels mitigate these risks and become more independent in their revenue generation.</p><p><strong>5. Control Over Guest Data :</strong>Direct bookings provide hotels with valuable guest data that can be used to analyze behavior, preferences, and patterns. This data can be leveraged to design targeted marketing campaigns, create tailored offers, and build comprehensive customer profiles. In contrast, OTA bookings often limit access to guest information, hampering the hotel’s ability to build effective marketing strategies.</p><p><strong>6. Flexibility in Cancellation Policies :</strong>Booking directly with hotels often allows greater flexibility in establishing cancellation policies, upselling opportunities, and additional services. This flexibility can be used to create more attractive offers and provide guests with more options for modifying or enhancing their bookings.</p><p><strong>7. Opportunities for Upselling and Cross-Selling :</strong>With direct bookings, hotels can take advantage of pre-arrival communication to upsell services such as room upgrades, spa packages, tours, or dining experiences. Hotels can also cross-sell related services, like airport transfers or city tours, which adds to the guest experience and boosts ancillary revenue streams.</p><h3><strong>Challenges in Direct Booking in Nepal</strong></h3><p><strong>Dominance of OTAs :</strong>OTAs like Booking.com, Agoda, Expedia, and Airbnb dominate the booking landscape in Nepal, offering hotels massive visibility to a global audience. However, the heavy reliance on these platforms makes it difficult for hotels to shift their focus to direct bookings. Additionally, OTAs charge high commissions (up to 30%), reducing the hotel’s profit margins.</p><p><strong>Lack of Digital Awareness :</strong>Many hotels in Nepal, particularly small and mid-range establishments, lack the technical knowledge or resources to build an effective online presence. Websites and booking engines are often poorly optimized or non-existent, making it hard for hotels to attract direct bookings through digital channels.</p><p><strong>Limited Online Marketing Strategies :</strong>Hotels that don’t invest in digital marketing strategies (SEO, social media, Google Ads, etc.) struggle to drive traffic to their own websites. This leads to over-dependence on OTAs, as they lack the skills to promote their direct booking channels effectively.</p><p><strong>Trust and Payment Issues :</strong>Many travelers, especially international ones, prefer to book through OTAs because they are considered reliable and provide guarantees in case of booking issues. Trust in local hotel websites for payments and services can be lower due to concerns over security, particularly in a region where online fraud and payment challenges exist.Additionally, limited payment gateway options (like PayPal, which isn’t widely used in Nepal) can hinder direct booking transactions.</p><p><strong>Inadequate Technology Infrastructure :</strong>The use of modern booking engines and integrated Property Management Systems (PMS) is still evolving. Many hotels operate using outdated systems or manual processes, making it difficult to seamlessly manage inventory and reservations across multiple channels, including direct bookings.</p><p><strong>User Experience on Hotel Websites :</strong>Even hotels that have websites often do not invest in user-friendly designs or mobile-responsive platforms. Poor website design and user experience can deter potential guests from booking directly.</p><p><strong>Lack of Loyalty Programs and Incentives :</strong>OTAs often offer user-friendly loyalty programs like Genius on Booking.com, making it more attractive for frequent travelers to use their services. Many Nepalese hotels, especially smaller ones, do not offer compelling incentives or loyalty programs for guests to book directly.</p><h3><strong>Problems</strong></h3><p><strong>1. Dominance of OTAs :</strong>Over-reliance on OTAs like Booking.com, Expedia, Agoda, and Airbnb is a significant barrier to direct bookings. OTAs offer broad visibility and convenience, making it easier for hotels to attract international travelers. However, they charge commissions as high as 15–30%, cutting into hotel profits.High competition on OTAs encourages hotels to offer the lowest possible prices on these platforms, leaving little incentive for customers to book directly through hotel websites.</p><p><strong>2. Lack of Online Presence and Poor Websites :</strong>Many hotels, especially smaller and mid-range establishments, do not have properly optimized websites. Those that do may have outdated designs, poor user experiences, or lack mobile optimization. This reduces the effectiveness of direct bookings.Booking engines on hotel websites are often basic, lacking advanced features like dynamic pricing, special offers, or loyalty programs, which OTAs provide.</p><p><strong>3. Limited Digital Marketing :</strong>Many hotels in Nepal do not invest adequately in digital marketing strategies such as SEO (Search Engine Optimization), social media marketing, and Google Ads. This makes it difficult to drive traffic to their websites and convert visitors into direct bookings.OTAs have strong marketing power, using aggressive advertising, loyalty programs, and high search engine rankings, which hotels find difficult to compete with.</p><p><strong>4. Trust and Security Concerns :</strong>Travelers, especially international tourists, tend to trust established OTAs over lesser-known hotel websites. This is due to concerns about the reliability of direct booking platforms, including security and customer service.Payment gateway limitations are also a challenge. While OTAs offer familiar and trusted payment options, many hotel websites in Nepal do not provide a wide range of secure payment methods, discouraging guests from booking directly.</p><p><strong>5. Lack of Localized and International Payment Options :</strong>Hotels in Nepal often struggle with integrating effective and trusted payment gateways on their websites. International travelers expect the convenience of payment methods like PayPal, Visa, or Mastercard, while local travelers may prefer eSewa, Khalti, or Fonepay.Inadequate payment options, or fear of fraud in online transactions, can make travelers hesitant to book directly.</p><p><strong>6. Low Customer Loyalty Programs :</strong>Unlike OTAs, which offer enticing loyalty programs (e.g., Booking.com’s Genius program), many hotels in Nepal do not have their own loyalty programs or incentives to encourage repeat direct bookings.Hotels that do have loyalty programs often do not market them well, and the benefits may not be as attractive as the rewards offered by OTAs.</p><p><strong>7. Technical Barriers for Smaller Hotels :</strong>Many small and independent hotels in Nepal lack the technical infrastructure or knowledge to implement modern booking engines and Property Management Systems (PMS). Without proper technology, it becomes challenging to handle real-time room inventory, process payments securely, or provide a seamless booking experience.Integrating hotel websites with channel managers and updating rates and availability across multiple platforms, including OTAs, is technically complex, and smaller hotels may struggle to manage this.</p><p><strong>8. Language and Localization Issues :</strong>Many hotel websites in Nepal do not offer multilingual support, which can deter international travelers from booking directly. A lack of localized content for different markets also prevents hotels from effectively targeting travelers from specific countries or regions.OTAs provide easy-to-understand booking experiences in multiple languages, which makes it more convenient for tourists.</p><p><strong>9. Limited Offerings and Booking Flexibility :</strong>Direct booking platforms on hotel websites may not offer the same level of flexibility and options as OTAs. For example, OTAs often allow for easy cancellation, modification of bookings, or comparisons of multiple properties, while hotel websites may not provide the same features.Hotels may struggle to match the dynamic pricing models, offers, and upsell opportunities available through OTAs, reducing the appeal of booking directly.</p><p><strong>10. Guest Perception and Lack of Trust in Smaller Brands :</strong>Smaller and lesser-known hotels often face trust issues. Travelers are more likely to book with a well-known brand through an OTA than directly with a smaller hotel they have no prior relationship with. This trust gap is exacerbated when hotels lack online reviews or a robust reputation.</p><p><strong>11. Lack of Direct Booking Incentives :</strong>Hotels in Nepal often fail to offer compelling incentives for guests to book directly, such as discounted rates, free upgrades, or additional perks (e.g., free airport transfer, breakfast, or late check-out). Without these incentives, travelers have little reason to move away from the convenience of OTAs.</p><p><strong>12. Inconsistent Online and Offline Coordination :</strong>Hotels may offer different rates or policies on their website compared to OTAs. This inconsistency can confuse travelers and discourage them from booking directly if they perceive the hotel’s own rates as less competitive or trustworthy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89345a8748fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micro-services vs Monolithic Architecture: A Case Study]]></title>
            <link>https://tamrakar-shreyaa.medium.com/micro-services-vs-monolithic-architecture-a-case-study-e003af61b615?source=rss-e6cf9555e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e003af61b615</guid>
            <category><![CDATA[monolithic-architecture]]></category>
            <category><![CDATA[prime-video]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[netflix]]></category>
            <category><![CDATA[case-study]]></category>
            <dc:creator><![CDATA[Tamrakar Shreyaa]]></dc:creator>
            <pubDate>Sun, 08 Dec 2024 10:44:33 GMT</pubDate>
            <atom:updated>2024-12-08T10:44:33.112Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7M38Me3lRdz7e3OI8iM5ZQ.png" /></figure><p><strong>Monolithic architecture :</strong>A <strong>monolithic architecture</strong> refers to a software design where all components and functions are tightly coupled into a single, unified application. In a monolithic application, the user interface, business logic, and data access layers are interconnected and typically share a single code base and database.</p><p><strong>Key Characteristics of a Monolithic Architecture:</strong></p><ol><li><strong>Single Code base</strong>: All application features and services reside within a single code base. Changes to the code require the whole application to be built and deployed.</li><li><strong>Tightly Coupled Components</strong>: Different modules or functions within the application are closely interdependent, making it harder to isolate failures or scale individual parts of the system.</li><li><strong>Centralized Database</strong>: Typically, a single, centralized database is used for managing data across the application.</li><li><strong>Single Deployment Unit</strong>: The entire application is packaged and deployed as one unit (e.g., a single JAR, WAR, or container image).</li></ol><p><strong>Advantages of Monolithic Architecture:</strong></p><ul><li><strong>Simplicity</strong>: Easier to develop, test, and deploy initially due to its unified code base.</li><li><strong>Performance</strong>: Because all components are within the same application, communication between them can be faster compared to distributed systems.</li><li><strong>Ease of Management</strong>: Simple deployments and well-understood development practices can be beneficial for smaller teams or projects.</li></ul><p><strong>Disadvantages of Monolithic Architecture:</strong></p><ul><li><strong>Limited Scalability</strong>: It’s challenging to scale specific parts of the application independently, leading to resource inefficiencies.</li><li><strong>Tight Coupling</strong>: Changes in one part of the system may affect other parts, making modifications, updates, and debugging more difficult.</li><li><strong>Long Deployment Times</strong>: As the application grows in size, deployment times can become longer, affecting development cycles.</li><li><strong>Difficult Maintenance</strong>: Managing a large code base in a monolithic structure can be challenging, especially as the application grows and the team expands.</li></ul><p><strong>Use Case:</strong>Monolithic architecture is a good choice for small to medium-sized applications or startups that are just starting out and don’t yet have complex scaling or modularization requirements. Once the application grows, organizations often transition to a micro-services architecture to overcome the limitations of monolithic systems.</p><p><strong>Micro-services architecture </strong>: software design approach where an application is composed of small, independent, and loosely coupled services. Each service is responsible for a specific business capability and communicates with other services through APIs (typically HTTP/REST or messaging systems). This contrasts with monolithic architecture, where the entire application is a single, tightly-coupled code base.</p><p><strong>Key Characteristics of Micro-services Architecture:</strong></p><ol><li><strong>Independent Services</strong>: Each service (or micro-service) focuses on a specific business function or domain, like user management, payment processing, or inventory management.</li><li><strong>Decentralized Data Management</strong>: Each micro-service often manages its own database or data storage, which allows for more flexible and independent data handling.</li><li><strong>Loose Coupling</strong>: Services are loosely coupled and communicate using well-defined interfaces (usually HTTP/REST, message queues, or event-driven systems).</li><li><strong>Autonomous Deployment</strong>: Each service can be independently developed, tested, deployed, and scaled. This enables continuous integration and delivery (CI/CD) practices.</li><li><strong>Technology Diversity</strong>: Teams have the freedom to choose the technology stack that best fits each micro-service’s requirements. For example, one service might be written in Node.js, another in Python, and yet another in Java.</li><li><strong>Domain-Driven Design (DDD)</strong>: Micro-services architecture often aligns with DDD principles, where the application is divided based on business domains and subdomains.</li></ol><p><strong>Advantages of Micro-services Architecture:</strong></p><ul><li><strong>Scalability</strong>: Individual services can be scaled independently, allowing for better resource utilization and handling of different workloads.</li><li><strong>Agility and Flexibility</strong>: Teams can work on different services simultaneously without impacting others, leading to faster development cycles.</li><li><strong>Fault Isolation</strong>: If one service fails, it doesn’t bring down the entire application, improving reliability and resilience.</li><li><strong>Technology Flexibility</strong>: Teams can use different technologies for different services based on the best fit for the service’s requirements.</li><li><strong>Easier Maintenance</strong>: Services are smaller in scope, making them easier to understand, maintain, and refactor over time.</li></ul><p><strong>Disadvantages of Micro-services Architecture:</strong></p><ul><li><strong>Complexity</strong>: Managing many services can become complex in terms of deployment, testing, versioning, and inter-service communication.</li><li><strong>Distributed Systems Challenges</strong>: Issues like network latency, data consistency, and distributed transactions require careful handling.</li><li><strong>Data Management Complexity</strong>: Decentralized databases and data stores lead to complexity in managing data consistency and handling cross-service queries.</li><li><strong>DevOps Overhead</strong>: CI/CD, monitoring, scaling, and deploying micro-services require more sophisticated DevOps practices and tools.</li></ul><p><strong>Common Patterns in Micro-services:</strong></p><ul><li><strong>API Gateway</strong>: Acts as an entry point for clients and routes requests to the appropriate services.</li><li><strong>Service Discovery</strong>: Helps services find each other, especially in dynamic environments.</li><li><strong>Event-Driven Architecture</strong>: Uses events to communicate between services asynchronously, enhancing decoupling.</li><li><strong>Saga Pattern</strong>: A way to manage distributed transactions in a micro-services setup without traditional, centralized database transactions.</li></ul><p><strong>Use Case:</strong>Micro-services architecture is ideal for large, complex applications that need to scale, support multiple teams working simultaneously, or frequently deploy new features. It is used by companies like Netflix, Amazon, Uber, and many others to handle millions of users and transactions efficiently.For organizations starting with smaller applications or with a simpler domain, transitioning from a monolithic to micro-services architecture can happen as the business requirements and complexities grow.</p><h3><strong>Netflix’s Case Study</strong></h3><p>Netflix is one of the first companies to have successfully migrated from a traditional.In fact, Netflix implemented this architecture long before the term micro-services was even introduced. It took more than two years for Netflix to achieve complete migration to the cloud. Not only did Netflix perfect the use of micro-services but it also managed to open source many of the tools which were used to build it. The Netflix OSS (Open Source Software Center) has a lot of tools and technologies which can be used by other companies to create micro-service architecture on the cloud.</p><p><strong>Reason for this Migration<br></strong>When Netflix announced its big move to the cloud they faced a lot of criticism as no one believed such a feat was possible at that time. The main reason why Netflix had decided to move to the cloud was due to its rapidly increasing data and user information that it was hard to store it in its current data centers, this caused a huge deal of problems. The solution was accomplished using Amazon Web Service (AWS), which promised to provide large computing resources and data centers with guaranteed security and reliability. With AWS scaling can be done within a couple of minutes without any user involvement. While moving to the cloud, Netflix managed to split its single monolithic application into hundreds of small loosely coupled services. Today Netflix has over a 1000 micro-services, each managing a separate part of the site.</p><p><strong>The Move<br></strong>According to the then cloud architect of Netflix, the migration process began in 2009. It started out by moving movie encoding, a non customer facing application. By 2010 Netflix started moving the remaining pieces to the cloud such as account signup, movie selections, and other configurations. By December 2011, Netflix had successfully migrated its entire operation to the cloud — from a monolithic to a then-unknown territory of micro-service architecture. Unlike how it looks, Netflix had to face a lot of problems during this big move. First of all, during the entire migration process, Netflix had to keep both its cloud servers and its in house servers running to ensure smooth working during this transition period. Also moving to the cloud meant replicating all the data from the local data centers to the cloud data centers, this involved having to deal with a huge amount of data. During the migration of customer-facing applications, Netflix had to deal with a lot of latency issues while serving the web pages. Netflix also faced a number of other issues such as load increases, instance failures, and other performance issues. What people considered as a crazy move by Netflix turned out to be a game-changer in the field of cloud computing today. Today almost all the big companies like Google, Twitter, IBM, Amazon have already moved to the cloud while other companies have slowly started their migration. Micro-service architecture has since become one of the important approaches to the cloud. When it comes to cloud computing today it is no surprise that Netflix has managed to come out as a technology leader.</p><h3><strong>Amazon Prime Video Case Study</strong></h3><p>Amazon Prime Video (APV) is one of the largest streaming platforms in the world, offering video-on-demand services to millions of users globally. To manage this enormous platform and provide a seamless experience, APV initially adopted a micro-services architecture. However, as the system grew, they encountered unexpected challenges and made strategic adjustments to find a balance between scalability and simplicity.</p><p><strong>The Initial Micro-services Architecture<br></strong>In the early days, Amazon Prime Video followed a micro-services approach, which allowed its teams to operate independently. The advantages of this architecture were clear:</p><ul><li><strong>Independent Deployments:</strong> Teams could deploy and release features without affecting the entire platform.</li><li><strong>Scalability:</strong> Each service could scale independently based on demand, reducing bottlenecks.</li><li><strong>Team Autonomy:</strong> Development teams could manage their own code bases and technology stacks.</li></ul><p><strong>Challenges with Micro-services</strong></p><p>Despite the initial benefits, APV soon realized that managing a massive fleet of micro-services came with significant drawbacks:</p><ol><li><strong>Increased Complexity:</strong> As the number of micro-services grew, the complexity of managing dependencies, service orchestration, and data consistency became overwhelming.</li><li><strong>Communication Overhead:</strong> Service-to-service communication introduced latency and required careful handling of APIs and network calls.</li><li><strong>Deployment Coordination:</strong> Even with independent deployments, coordinating and maintaining consistency between services became a challenge.</li><li><strong>Debugging and Monitoring:</strong> Identifying issues in a micro-services ecosystem proved difficult due to distributed logging and monitoring requirements.</li></ol><p><strong>Transition to a Modular Monolith<br></strong>Amazon Prime Video recognized that maintaining a micro-services architecture across all areas of the platform was counterproductive for their goals. They made a strategic decision to move towards a more <strong>modular monolith</strong>:</p><ol><li><strong>Definition of a Modular Monolith:</strong> A modular monolith is a single code base with clear, well-defined boundaries between modules. These modules can be developed and maintained separately within a unified deployment, avoiding the overhead of service-to-service communication.</li><li><strong>Hybrid Approach:</strong> Not all micro-services were merged into the monolithic code base. Amazon Prime Video strategically retained some critical or highly decoupled micro-services where autonomy, scalability, or independent deployments were essential.</li><li><strong>Key Benefits of the Shift:</strong></li></ol><ul><li><strong>Reduced Latency:</strong> By consolidating certain functions within the same code base, Amazon Prime Video was able to minimize the latency caused by inter-service communication.</li><li><strong>Simplified Deployment and Testing:</strong> A modular monolith made it easier to coordinate deployments and manage dependencies, reducing the risk of version mismatches between services.</li><li><strong>Improved Debugging:</strong> A unified code base allowed for better logging and monitoring, making it easier to trace and fix issues across the system.</li></ul><p><strong>Key Lessons from Amazon Prime Video’s Case Study</strong></p><ul><li><strong>Choose the Right Architecture for the Right Use Case:</strong> Not all services or features require micro-services. A modular monolith can provide better efficiency and reliability for parts of the system that require tight integration.</li><li><strong>Minimize Complexity Where Possible:</strong> Managing too many services can lead to coordination challenges, latency issues, and increased operational overhead. Simplification and consolidation can significantly improve overall efficiency.</li><li><strong>Focus on Modularity:</strong> Even within a monolithic architecture, it’s crucial to maintain clear module boundaries to allow for flexibility, scalability, and independent development by different teams.</li><li><strong>Balance Performance and Scalability:</strong> Amazon Prime Video’s hybrid model allows them to retain the benefits of both approaches, scaling independently where needed while reducing latency and deployment issues in tightly-coupled services.</li></ul><p><strong>Conclusion<br></strong>Amazon Prime Video’s decision to shift from a pure micro-services architecture to a modular monolith highlights an essential point: there’s no one-size-fits-all solution. Architecture should evolve with the product, team structure, and business needs. By embracing a modular monolith, APV found the sweet spot between scalability and simplicity, delivering a smoother experience to millions of users worldwide.</p><p><strong>Additional Resources</strong></p><ul><li>For more details on modular monoliths and hybrid architecture models, you can look into <strong>Domain-Driven Design (DDD)</strong> principles and how to structure code with <strong>bounded contexts</strong>.</li><li>Case studies of other companies like <strong>Segment</strong> and <strong>Twitter</strong> provide additional insights into why and how companies revert or partially consolidate their micro-services architecture.</li></ul><h3><strong>Why big company shift form Micro-services to Monolith</strong></h3><p><strong>1. Increased Infrastructure Costs<br>Micro-services:</strong> Running micro-services usually requires a more complex infrastructure setup. Each micro-service may have its own database, server, or storage requirements, leading to:</p><ul><li>Higher cloud hosting costs due to the number of individual services.</li><li>Multiple databases, containers, virtual machines, and sometimes redundant services.</li><li>The need for orchestration tools like Kubernetes or Docker Swarm, which increase both setup complexity and resource consumption.</li></ul><p><strong>Monolith:</strong> A monolithic approach centralizes resources, meaning fewer database instances and server deployments. This reduces overall cloud resource utilization and related costs.</p><p><strong>2. Operational and Maintenance Overhead<br>Micro-services:</strong> Micro-services require more operational expertise and maintenance. DevOps teams need to manage and monitor multiple services, handle complex deployments, ensure inter-service communication, and maintain various CI/CD pipelines. This complexity leads to:</p><ul><li>Increased DevOps and infrastructure engineering costs.</li><li>Higher expenses on monitoring tools and services (e.g., Datadog, Prometheus, distributed tracing solutions).</li></ul><p><strong>Monolith:</strong> A monolith is easier to maintain and deploy because it typically requires fewer pipelines, tools, and configurations. This means lower staffing costs for DevOps and infrastructure management.</p><p><strong>3. Cost of Team Coordination and Communication<br>Micro-services:</strong> In a large micro-services architecture, each service is managed by a different team. This setup increases the need for coordination and cross-team communication. Without a cohesive strategy and strong alignment between teams, this can lead to:</p><ul><li>Higher management costs due to increased meetings, coordination efforts, and internal communication.</li><li>Development delays due to synchronization requirements between services.</li></ul><p><strong>Monolith:</strong> A monolithic architecture simplifies team communication since the teams are working on a unified code base with a single deployment. This can reduce the number of meetings and coordination efforts, thereby lowering management and collaboration costs.</p><p><strong>4. Development and Debugging Time Costs<br>Micro-services:</strong> Developing, testing, and debugging in a micro-services environment is often more time-consuming. You have to deal with:</p><ul><li>Testing dependencies across services, which requires a sophisticated testing strategy.</li><li>Distributed logging and tracing costs to monitor interactions between micro-services.</li><li>Time and effort in fixing bugs that can cascade across multiple services, which delays releases.</li></ul><p><strong>Monolith:</strong> Debugging and testing are easier and cheaper in a monolithic architecture because everything is in one place. This simplicity means fewer hours spent on development and testing, translating to lower labor costs.</p><p><strong>5. Cost of Distributed Data Management<br>Micro-services:</strong> Micro-services architectures often require distributed databases, leading to complexities in ensuring data consistency, partitioning, and synchronization. Managing data across different services can introduce:</p><ul><li>Additional expenses for data synchronization and redundancy.</li><li>More complex data infrastructure requirements, leading to increased costs for DBAs (Database Administrators) and data engineers.</li></ul><p><strong>Monolith:</strong> In a monolithic architecture, data is typically managed in a single database or well-organized database instances, reducing the complexity and cost of managing distributed data.</p><p><strong>6. Cost of Specialized Tools and Technologies<br>Micro-services:</strong> Running a micro-services-based architecture usually requires a range of specialized tools for:</p><ul><li>Service orchestration (e.g., Kubernetes, Docker Swarm).</li><li>API gateways and service meshes (e.g., Istio, Linkerd).</li><li>Distributed monitoring, logging, and tracing (e.g., ELK Stack, Prometheus, Jaeger).</li></ul><p>These tools come with costs associated with licensing, infrastructure requirements, training, and maintenance.</p><p><strong>Monolith:</strong> A monolith needs fewer specialized tools and often relies on simpler frameworks and technologies, leading to reduced licensing and technology costs.</p><h3>Why big company shift form Monolith to Micro-services</h3><p>Big companies shift from a monolithic architecture to a micro-services architecture primarily to address the challenges of scaling, flexibility, team autonomy, and maintainability. As organizations grow, so do their applications, user base, and teams. A monolithic architecture, which often serves well in the early stages, starts to show limitations. Here’s why big companies make the shift to micro-services:</p><p><strong>1. Scalability</strong></p><ul><li><strong>Challenge in Monolith:</strong> Scaling a monolithic application usually means scaling the entire application even if only certain components or services experience high demand. This leads to inefficient use of resources.</li><li><strong>Micro-services Advantage:</strong> Micro-services allow independent scaling of services based on their specific needs. For example, if the payment service experiences high load, it can be scaled separately from the user authentication or inventory services, optimizing resource utilization.</li></ul><p><strong>2. Independent Deployability</strong></p><ul><li><strong>Challenge in Monolith:</strong> In a monolithic application, changes to any part of the code base often require redeploying the entire application. This can lead to longer release cycles and higher risks during deployment.</li><li><strong>Micro-services Advantage:</strong> With micro-services, different services can be <strong>deployed independently</strong>, allowing for faster and more frequent releases. Each micro-service can be developed, tested, and deployed separately, which means teams can deliver new features or bug fixes more quickly without affecting the entire system.</li></ul><p><strong>3. Improved Fault Isolation</strong></p><ul><li><strong>Challenge in Monolith:</strong> If a single component in a monolithic application fails, it can potentially bring down the entire system, leading to higher downtime and impact on users.</li><li><strong>Micro-services Advantage:</strong> Micro-services architecture promotes <strong>fault isolation</strong>. If one service fails, other services continue running, minimizing the impact on users and the business. This allows better resilience and reliability.</li></ul><p><strong>4. Technological Flexibility</strong></p><ul><li><strong>Challenge in Monolith:</strong> Monolithic applications are typically built using a single technology stack. If an organization wants to adopt new technologies, they often face difficulties in a tightly coupled monolithic architecture.</li><li><strong>Micro-services Advantage:</strong> Each micro-service can be built with the most appropriate technology stack for its specific use case. This flexibility allows teams to experiment with new technologies and avoid technology lock-in, ensuring that they can innovate faster.</li></ul><p><strong>5. Faster Development and Deployment by Autonomous Teams</strong></p><ul><li><strong>Challenge in Monolith:</strong> As the monolith grows, the code base becomes large and complex. Multiple teams working on the same code base can create bottlenecks in development, testing, and release processes, leading to slower releases and more coordination issues.</li><li><strong>Micro-services Advantage:</strong> Micro-services allow companies to organize teams around services. Each team can be responsible for developing, deploying, and maintaining a specific service independently, allowing for a more agile and DevOps-oriented approach. This results in greater team autonomy and faster delivery of features.</li></ul><p><strong>6. Better Maintainability and Modularity</strong></p><ul><li><strong>Challenge in Monolith:</strong> A large monolithic code-base can become challenging to understand, maintain, and refactor. Making a change often affects multiple parts of the code-base, leading to risks of introducing bugs.</li><li><strong>Micro-services Advantage:</strong> Micro-services promote a modular approach, making each service smaller and more manageable. Teams can focus on a single service at a time, improving code maintainability and reducing the risk of introducing errors across the entire application.</li></ul><p><strong>7. Support for Continuous Delivery and DevOps</strong></p><ul><li><strong>Challenge in Monolith:</strong> Monolithic applications often involve tightly coupled components, making CI/CD pipelines more complicated. It can be challenging to implement automated testing, deployment, and monitoring at a granular level.</li><li><strong>Micro-services Advantage:</strong> Micro-services enable organizations to embrace DevOps practices such as Continuous Integration and Continuous Deployment (CI/CD) more effectively. Teams can automate the testing, deployment, and monitoring of individual services, which improves efficiency and reliability in delivering software.</li></ul><p><strong>8. Enhanced Agility and Speed of Innovation</strong></p><ul><li><strong>Challenge in Monolith:</strong> In a monolith, adding new features or services may require extensive changes to the existing code base, leading to slower delivery and decreased agility. Teams may also be reluctant to experiment with new ideas due to the risk of breaking existing functionality.</li><li><strong>Micro-services Advantage:</strong> By decomposing an application into smaller, independently developed services, micro-services allow for faster experimentation and innovation.<strong> </strong>Teams can try new ideas, implement new features, or iterate quickly without disrupting the entire system.</li></ul><p><strong>9. Improved Resilience and Error Recovery</strong></p><ul><li><strong>Challenge in Monolith:</strong> A single point of failure in a monolithic architecture can result in significant downtime. Detecting and fixing issues also becomes more complex when everything is tightly coupled.</li><li><strong>Micro-services Advantage:</strong> Micro-services architectures are designed to be more resilient to failures. By isolating services and implementing fault tolerance strategies, companies can limit the blast radius of failures and recover more quickly.</li></ul><p><strong>10. Geographic and Organizational Scaling</strong></p><ul><li><strong>Challenge in Monolith:</strong> For large organizations with globally distributed teams, managing and developing a monolithic application becomes increasingly complex. Cross-team communication and collaboration can slow down due to the centralized code base.</li><li><strong>Micro-services Advantage:</strong> With micro-services, different teams can own different services. This team autonomy and service ownership model enable large organizations to scale their engineering operations more effectively, accommodating globally distributed teams.</li></ul><ul><li><a href="https://tamrakar-shreyaa.medium.com/how-to-setup-multiple-github-accounts-on-ubuntu-7e0f5983692f">How to setup multiple GitHub accounts on Ubuntu</a></li><li><a href="https://tamrakar-shreyaa.medium.com/communication-with-the-database-via-rabbitmq-messages-in-a-laravel-microservice-application-484c58d55289">Communication with the database via RabbitMQ messages in a Laravel Microservice application</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e003af61b615" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep Dive into Implementing Kafka in NestJS for Event-Driven]]></title>
            <link>https://tamrakar-shreyaa.medium.com/a-deep-dive-into-implementing-kafka-in-nestjs-for-event-driven-f752bc2c1323?source=rss-e6cf9555e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f752bc2c1323</guid>
            <category><![CDATA[message-broker]]></category>
            <category><![CDATA[event-driven]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Tamrakar Shreyaa]]></dc:creator>
            <pubDate>Sat, 19 Oct 2024 15:41:37 GMT</pubDate>
            <atom:updated>2024-10-19T15:41:37.821Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DxY2Fkn89mkHMxfC74Niig.jpeg" /></figure><h3><strong>A brief overview of Apache Kafka:</strong></h3><p>Apache Kafka is an open-source distributed event streaming platform used to handle real-time data feeds. It is designed to handle a high volume, high throughput, and low latency data streams, and can be used to process, store, and analyze data in real-time. Kafka can be used to build real-time streaming data pipelines and applications and is often used in combination with Apache Storm, Apache<a href="https://www.geeksforgeeks.org/hadoop-features-of-hadoop-which-makes-it-popular/"> </a>Hadoop, and Apache<a href="https://www.geeksforgeeks.org/overview-of-apache-spark/"> </a>Spark.</p><h3>What event-driven architecture is:</h3><p>Event-Driven Architecture (EDA) involves communication between services through the exchange of events. Events represent significant occurrences or state changes within the system and are typically published to event streams or topics. Services react to events asynchronously, enabling loosely coupled and responsive architectures.</p><p>Communication between services in a decoupled manner is crucial. This is where Kafka, a distributed event streaming platform, comes into play.</p><p>Let’s get started!</p><h4>Step 1: Create a NestJS backend</h4><pre>npx @nestjs/cli new kafka-nestjs</pre><h4>Step 2: Setup Docker yml file</h4><p>Firstly, you need to have Docker installed and running.</p><p>create a file named docker-compose.yml and copy-paste the following:</p><pre>version: &#39;3.8&#39;<br>services:<br>  postgres:<br>    image: postgres:latest<br>    container_name: postgres_demo<br>    environment:<br>      POSTGRES_USER: ${POSTGRES_USER}<br>      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}<br>      POSTGRES_DB: ${POSTGRES_DB}<br>    ports:<br>      - &quot;${POSTGRES_PORT}:5432&quot;<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data<br><br>  zookeeper:<br>    image: wurstmeister/zookeeper:latest<br>    container_name: zookeeper<br>    ports:<br>      - &quot;2181:2181&quot;<br>    networks:<br>      - my-network<br><br>  kafka:<br>    image: wurstmeister/kafka:2.13-2.8.1<br>    container_name: kafka<br>    environment:<br>      KAFKA_ADVERTISED_LISTENERS: INSIDE://kafka:9093,OUTSIDE://localhost:9092<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INSIDE:PLAINTEXT,OUTSIDE:PLAINTEXT<br>      KAFKA_LISTENERS: INSIDE://0.0.0.0:9093,OUTSIDE://0.0.0.0:9092<br>      KAFKA_INTER_BROKER_LISTENER_NAME: INSIDE<br>      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181<br>      KAFKA_CREATE_TOPICS: &quot;audit-log:1:1,api-log:1:1&quot;<br>    ports:<br>      - &quot;9092:9092&quot;<br>    depends_on:<br>      - zookeeper<br>    networks:<br>      - my-network<br><br>  nestjs-app:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    ports:<br>      - &quot;3000:3000&quot;<br>    depends_on:<br>      - postgres<br><br>volumes:<br>  postgres_data:<br><br>networks:<br>  my-network:</pre><ul><li>This docker-compose.yml defines four services (PostgreSQL, Zookeeper, Kafka, and a NestJS application) and sets up how they communicate and interact with each other.</li><li>Docker Compose will orchestrate the starting and linking of these services in a single command (docker-compose up), managing networking, environment variables, and container dependencies automatically.</li></ul><p>create a file named Dockerfile and copy-paste the following:</p><pre># Use an official Node runtime as a parent image<br>FROM node:18<br><br># Set the working directory<br>WORKDIR /usr/src/app<br><br># Install dependencies and utilities<br>RUN apt-get update &amp;&amp; \<br>    apt-get install -y iputils-ping netcat-openbsd<br><br># Copy package.json and package-lock.json to the working directory<br>COPY package*.json ./<br><br># Install dependencies<br>RUN npm install<br><br># Copy the rest of the application code to the working directory<br>COPY . .<br><br># Build the NestJS application<br>RUN npm run build<br><br># Expose the port the app runs on<br>EXPOSE 3000<br><br># Define the command to run the app<br>CMD [&quot;npm&quot;, &quot;run&quot;, &quot;start:prod&quot;]</pre><h4>Step 3: Setup Prisma (ORM)</h4><pre>npm install -D prisma<br>npm install @prisma/client<br>npx prisma init</pre><p>This will create two new files: schema.prisma and .env.</p><p>Update .env file :</p><pre># Environment variables declared in this file are automatically made available to Prisma.<br># See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema<br><br># Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.<br># See the documentation for all the connection string options: https://pris.ly/d/connection-strings<br><br># PostgreSQL environment variables<br>POSTGRES_USER=postgres<br>POSTGRES_PASSWORD=######<br>POSTGRES_DB=kafka_nestjs<br>POSTGRES_PORT=5432<br><br><br># NestJS environment variables<br>DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${POSTGRES_PORT}/${POSTGRES_DB}<br><br># mail<br>MAIL_HOST=smtp.gmail.com<br>MAIL_USER=#######<br>MAIL_PASSWORD=#######<br>MAIL_FROM=noreply@example.com</pre><p>Update schema.prisma file :</p><pre>generator client {<br>  provider = &quot;prisma-client-js&quot;<br>}<br><br>datasource db {<br>  provider = &quot;postgresql&quot;<br>  url      = env(&quot;DATABASE_URL&quot;)<br>}<br><br>model users {<br>  id                    Int       @id @default(autoincrement())<br>  username              String    @db.VarChar(100)<br>  email                 String    @unique @db.VarChar(255)<br>  password_hash         String    @db.VarChar(255)<br>  is_active             Boolean   @default(true)<br>  created_at            DateTime? @default(now()) @db.Timestamp(6)<br>  updated_at            DateTime? @default(now()) @db.Timestamp(6)<br><br>}</pre><h4>Step 4: Generate and apply a migration</h4><pre> npx prisma migrate dev &quot;new&quot;<br> npx prisma migrate deploy<br> npx prisma generate</pre><h4>Step 5: Connect to the database</h4><pre>npx @nestjs/cli g module prisma<br>npx @nestjs/cli g service prisma</pre><p>Update prisma.module.ts file :</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { PrismaService } from &#39;./prisma.service&#39;;<br><br>@Module({<br>  providers: [PrismaService],<br>  exports: [PrismaService],<br>})<br>export class PrismaModule {}</pre><p>Update prisma.service.ts file :</p><pre>import { Injectable, OnModuleInit, OnModuleDestroy } from &#39;@nestjs/common&#39;;<br>import { PrismaClient } from &#39;@prisma/client&#39;;<br><br>@Injectable()<br>export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {<br>  <br>  async onModuleInit() {<br>    await this.$connect();<br>  }<br><br>  async onModuleDestroy() {<br>    await this.$disconnect();<br>  }<br>}</pre><p>For this to work, you also need to install @nestjs/config:</p><pre>npm install @nestjs/config</pre><pre>// src/app.module.ts<br>import { Module } from &#39;@nestjs/common&#39;;<br>import { AppController } from &#39;./app.controller&#39;;<br>import { AppService } from &#39;./app.service&#39;;<br>import { PrismaModule } from &#39;./prisma/prisma.module&#39;;<br>import { UsersModule } from &#39;./users/users.module&#39;;<br>import { MailModule } from &#39;./mail/mail.module&#39;;<br>import { ConfigModule } from &#39;@nestjs/config&#39;;<br>import configuration from &#39;./configuration&#39;;<br>import { KafkaModule } from &#39;./kafka/kafka.module&#39;;<br>import { KafkaConsumerService } from &#39;./kafka/kafka-consumer.service&#39;;<br><br>@Module({<br>  imports: [<br>    <br>    ConfigModule.forRoot({<br>      load: [configuration],<br>      isGlobal: true,<br>    }),<br>    PrismaModule, UsersModule, MailModule, KafkaModule],<br>  controllers: [AppController],<br>  providers: [AppService,KafkaConsumerService],<br>  exports: [KafkaConsumerService],<br>})<br>export class AppModule {}</pre><p>Create <strong>src/configuration.ts</strong></p><pre>//src/configuration.ts<br>export default () =&gt; ({<br>    database: {<br>      url: process.env.DATABASE_URL,<br>    }<br>  });</pre><h4>Step 6: Install swagger and Kafka Dependencies</h4><pre>npm install --save @nestjs/swagger<br><br>npm install kafkajs @nestjs/microservices</pre><p>update in <strong>main.ts</strong> file</p><pre>// src/main.ts<br><br>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>import { PrismaClient } from &#39;@prisma/client&#39;;<br>import { DocumentBuilder, SwaggerModule } from &#39;@nestjs/swagger&#39;;<br>import { ValidationPipe } from &#39;@nestjs/common&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br><br><br>  app.useGlobalPipes(new ValidationPipe({ whitelist: true }));<br><br>  const config = new DocumentBuilder()<br>    .setTitle(&#39;project&#39;)<br>    .setDescription(&#39;The project API description&#39;)<br>    .setVersion(&#39;0.1&#39;)<br>    .addBearerAuth()<br>    .build();<br>  const document = SwaggerModule.createDocument(app, config);<br>  SwaggerModule.setup(&#39;api&#39;, app, document);<br><br>  await app.listen(3000);<br>}<br>bootstrap();</pre><h4>Step 7: Create a Controller</h4><pre>npx @nestjs/cli g resource users<br>npm install class-validator<br>npm install class-transformer<br>npm install bcrypt</pre><p>add following code in <strong>create-user.dto.ts</strong></p><pre>import { ApiProperty } from &quot;@nestjs/swagger&quot;<br>import { IsBoolean, IsEmail, IsOptional, IsString, MinLength } from &quot;class-validator&quot;;<br><br>export class CreateUserDto {<br><br>    @ApiProperty({ example: &#39;john_doe&#39;, description: &#39;The username of the user&#39; })<br>    @IsString()<br>    @MinLength(3)<br>    username: string;<br>  <br>    @ApiProperty({ example: &#39;john.doe@example.com&#39;, description: &#39;The email of the user&#39; })<br>    @IsEmail()<br>    email: string;<br>  <br>    @ApiProperty({ example: &#39;password123&#39;, description: &#39;The password of the user&#39; })<br>    @IsString()<br>    @MinLength(6)<br>    password_hash: string;<br>  <br>    @IsBoolean()<br>    @IsOptional()<br>    is_active?: boolean;<br><br>  }</pre><p>add following code in <strong>users.controller.ts</strong></p><pre>import {<br>  Controller,<br>  Get,<br>  Post,<br>  Body,<br>  Patch,<br>  Param,<br>  Delete,<br>  ParseIntPipe<br>} from &#39;@nestjs/common&#39;;<br>import { UsersService } from &#39;./users.service&#39;;<br>import { CreateUserDto } from &#39;./dto/create-user.dto&#39;;<br>import { UpdateUserDto } from &#39;./dto/update-user.dto&#39;;<br>import {<br>  ApiTags<br>} from &#39;@nestjs/swagger&#39;;<br><br>@Controller(&#39;users&#39;)<br>@ApiTags(&#39;users&#39;)<br><br>export class UsersController {<br>  constructor(private readonly usersService: UsersService) { }<br><br>  @Post()<br>  async create(@Body() createUserDto: CreateUserDto) {<br>    const users = await this.usersService.create(createUserDto);<br>    return users;<br>  }<br><br>  @Get()<br>  async findAll() {<br>    const users = await this.usersService.findAll();<br>    return users;<br>  }<br><br>  @Get(&#39;:id&#39;)<br>  async findOne(@Param(&#39;id&#39;, ParseIntPipe) id: number) {<br>    const users = await this.usersService.findOne(id);<br>    return users;<br>  }<br><br>  @Patch(&#39;:id&#39;)<br>  async update(<br>    @Param(&#39;id&#39;, ParseIntPipe) id: number,<br>    @Body() updateUserDto: UpdateUserDto,<br>  ) {<br>    const users = await this.usersService.update(id, updateUserDto);<br>    return users;<br>  }<br><br>  @Delete(&#39;:id&#39;)<br>  async remove(@Param(&#39;id&#39;, ParseIntPipe) id: number) {<br>    const deletedUser = await this.usersService.remove(id);<br>    return { success: true, data: deletedUser };<br>  }<br>}</pre><p>add following code in <strong>users.module.ts</strong></p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { UsersService } from &#39;./users.service&#39;;<br>import { UsersController } from &#39;./users.controller&#39;;<br>import { PrismaModule } from &#39;src/prisma/prisma.module&#39;;<br>import { KafkaProducerService } from &#39;src/kafka/kafka-producer.service&#39;;<br>import { KafkaModule } from &#39;src/kafka/kafka.module&#39;;<br><br>@Module({<br>  controllers: [UsersController],<br>  providers: [UsersService],<br>  imports: [PrismaModule,KafkaModule], <br>  exports: [UsersService]<br><br><br>})<br>export class UsersModule {}</pre><p>add following code in <strong>users.service.ts</strong></p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { PrismaService } from &#39;src/prisma/prisma.service&#39;;<br>import { CreateUserDto } from &#39;./dto/create-user.dto&#39;;<br>import { UpdateUserDto } from &#39;./dto/update-user.dto&#39;;<br>import * as bcrypt from &#39;bcrypt&#39;;<br>import { KafkaProducerService } from &#39;src/kafka/kafka-producer.service&#39;;<br><br>export const roundsOfHashing = 10;<br><br>@Injectable()<br>export class UsersService {<br>  constructor(private prisma: PrismaService,<br>    private readonly kafkaProducerService: KafkaProducerService) { }<br><br>  async create(createUserDto: CreateUserDto) {<br>    const hashedPassword = await bcrypt.hash(<br>      createUserDto.password_hash,<br>      roundsOfHashing,<br>    );<br>  // Emit Kafka event after registering the user<br>    await this.kafkaProducerService.emitUserRegisteredEvent(createUserDto);<br>    createUserDto.password_hash = hashedPassword;<br>    return this.prisma.users.create({<br>      data: createUserDto,<br>    });<br>  }<br><br><br>  findAll() {<br>    return this.prisma.users.findMany();<br>  }<br><br>  findOne(id: number) {<br>    return this.prisma.users.findUnique({ where: { id } });<br>  }<br><br>  async update(id: number, updateUserDto: UpdateUserDto) {<br>    if (updateUserDto.password_hash) {<br>      updateUserDto.password_hash = await bcrypt.hash(<br>        updateUserDto.password_hash,<br>        roundsOfHashing,<br>      );<br>    }<br><br>    return this.prisma.users.update({<br>      where: { id },<br>      data: updateUserDto,<br>    });<br>  }<br><br>  async remove(id: number) {<br>    return this.prisma.users.delete({<br>      where: { id },<br>    });<br>  }<br>}</pre><h4>Step 8: Email setup</h4><p>Add the @nestjs-modules/mailer and the peer dependency nodemailer</p><pre>npm install --save @nestjs-modules/mailer nodemailer<br>npm install --save-dev @types/nodemailer</pre><p>create a mail module and service via the Nest CLI and followed by creating a templates folder.</p><pre>npx @nestjs/cli g module mail<br>npx @nestjs/cli g service mail<br><br>mkdir src/mail/templates</pre><p>now update <strong>mail.module.ts</strong> file</p><pre>import { MailerModule } from &#39;@nestjs-modules/mailer&#39;;<br>import { HandlebarsAdapter } from &#39;@nestjs-modules/mailer/dist/adapters/handlebars.adapter&#39;;<br>import { Module } from &#39;@nestjs/common&#39;;<br>import { MailService } from &#39;./mail.service&#39;;<br>import { join } from &#39;path&#39;;<br>import { ConfigModule, ConfigService } from &#39;@nestjs/config&#39;;<br><br>@Module({<br>  imports: [<br>    MailerModule.forRootAsync({<br>      useFactory: async (config: ConfigService) =&gt; ({<br>      <br>        transport: {<br>          host: config.get(&#39;MAIL_HOST&#39;),<br>          secure: false,<br>          auth: {<br>            user: config.get(&#39;MAIL_USER&#39;),<br>            pass: config.get(&#39;MAIL_PASSWORD&#39;),<br>          },<br>        },<br>        defaults: {<br>          from: `&quot;No Reply&quot; &lt;${config.get(&#39;MAIL_FROM&#39;)}&gt;`,<br>        },<br>        template: {<br>          dir: join(__dirname, &#39;templates&#39;),<br>          adapter: new HandlebarsAdapter(),<br>          options: {<br>            strict: true,<br>          },<br>        },<br>      }),<br>      inject: [ConfigService],<br>    }),<br>  ],<br>  providers: [MailService],<br>  exports: [MailService],<br>})<br>export class MailModule {}</pre><p>Create your first email template registration.hbs in the src/mail/templates folder. Add the following simple template for a user confirmation.</p><pre>//src/mail/templates/registration.hbs<br><br> &lt;html&gt;<br>  &lt;body&gt;<br>    &lt;h1&gt;Welcome, {{name}}!&lt;/h1&gt;<br>    &lt;p&gt;Thank you for registering with us.&lt;/p&gt;<br>  <br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>By default, Nest <strong>only</strong> distributes TypeScript compiled files (.js and .d.ts) during the build step. To distribute your .hbs files, open your nest-cli.json and add your templates directory</p><pre><br>{<br>  &quot;$schema&quot;: &quot;https://json.schemastore.org/nest-cli&quot;,<br>  &quot;collection&quot;: &quot;@nestjs/schematics&quot;,<br>  &quot;sourceRoot&quot;: &quot;src&quot;,<br>  &quot;compilerOptions&quot;: {<br>    &quot;deleteOutDir&quot;: true,<br>    &quot;assets&quot;: [&quot;mail/templates/**/*&quot;]<br>  }<br>}</pre><p>Add MailerService to your own MailService and implement your mailing logic here. Let&#39;s send a user confirmation email using the template registration.hbs. You need to provide {{ name }} under the context key</p><pre><br>import { MailerService } from &#39;@nestjs-modules/mailer&#39;;<br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { users } from &#39;@prisma/client&#39;;<br><br>@Injectable()<br>export class MailService {<br>  constructor(private mailerService: MailerService) {}<br> async sendUserRegistration(user: users) {<br><br>    await this.mailerService.sendMail({<br>      to: user.email,<br>      from: &#39;&quot;Support Team&quot; &lt;support@example.com&gt;&#39;, // override default from<br>      subject: &#39;Welcome to Nice App! Confirm your Email&#39;,<br>      template: &#39;./registration&#39;, // `.hbs` extension is appended automatically<br>      context: { // ✏️ filling curly brackets with content<br>        name: user.username,<br>       <br>      },<br>    });<br>  }<br>}</pre><h4>Step 8: Setup Kafka Producer (Sending Events) and Kafka Consumer (Listening to Events)</h4><pre><br>npx @nestjs/cli g module kafka</pre><pre>// src/kafka/kafka.module.ts<br>import { Module } from &#39;@nestjs/common&#39;;<br>import { ClientsModule, Transport } from &#39;@nestjs/microservices&#39;;<br>import { PrismaModule } from &#39;src/prisma/prisma.module&#39;;<br>import { KafkaProducerService } from &#39;./kafka-producer.service&#39;;<br>import { KafkaConsumerService } from &#39;./kafka-consumer.service&#39;;<br>import { MailModule } from &#39;src/mail/mail.module&#39;;<br><br>@Module({<br>  imports: [<br>    ClientsModule.register([<br>      {<br>        name: &#39;KAFKA_SERVICE&#39;,<br>        transport: Transport.KAFKA,<br>        options: {<br>          client: {<br>            clientId: &#39;nestjs-kafka&#39;,<br>            brokers: [&#39;localhost:9092&#39;],<br>            retry: {<br>              retries: 10, // Number of retries<br>              initialRetryTime: 300, // Initial retry time in ms<br>              maxRetryTime: 10000, // Maximum total retry time in ms<br>              factor: 0.2, // Exponential factor for backoff<br>            },<br>          },<br>          consumer: {<br>            groupId: &#39;nestjs-group&#39;,<br>          },<br>        },<br>      },<br>    ]),<br>    PrismaModule,<br>   MailModule<br>  ],<br>  providers: [KafkaProducerService, KafkaConsumerService],<br>  exports: [KafkaProducerService],<br>})<br>export class KafkaModule { }</pre><pre>//  create file src/kafka/kafka-producer.service.ts<br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { Kafka } from &#39;kafkajs&#39;;<br><br>@Injectable()<br>export class KafkaProducerService {<br>  private readonly kafka = new Kafka({<br>    brokers: [&#39;localhost:9092&#39;],<br>  });<br>  private readonly producer = this.kafka.producer();<br><br>  constructor() {<br>    this.producer.connect().catch(console.error);<br>  }<br>async emitUserRegisteredEvent(userData: any) {<br>    await this.producer.send({<br>      topic: &#39;user-registered&#39;, // Topic name<br>      messages: [<br>        { key: &#39;user-registration&#39;, value: JSON.stringify(userData) },<br>      ],<br>    });<br>  }<br><br>  async onModuleDestroy() {<br>    await this.producer.disconnect();<br>  }<br>}</pre><pre>// create file src/kafka/kafka-consumer.service.ts<br>import { Injectable, OnModuleInit, Logger } from &#39;@nestjs/common&#39;;<br>import { Kafka } from &#39;kafkajs&#39;;<br>import { MailService } from &#39;src/mail/mail.service&#39;;<br><br>@Injectable()<br>export class KafkaConsumerService implements OnModuleInit {<br>  private readonly kafka = new Kafka({<br>    clientId: &#39;nestjs-kafka&#39;,<br>    brokers: [&#39;localhost:9092&#39;],<br>  });<br><br>  private readonly consumer = this.kafka.consumer({ groupId: &#39;nestjs-group&#39; });<br>  private readonly logger = new Logger(KafkaConsumerService.name);<br><br>  constructor(<br>    private readonly mailService: MailService,<br>  <br>) { }<br><br>async onModuleInit() {<br>   <br>    await this.consumer.connect();<br>    await this.consumer.subscribe({ topic: &#39;user-registered&#39;, fromBeginning: true });<br><br>    await this.consumer.run({<br>      eachMessage: async ({ topic, partition, message }) =&gt; {<br>        const userData = JSON.parse(message.value.toString());<br>        console.log(`Received user registration event: ${JSON.stringify(userData)}`);<br>        await this.mailService.sendUserRegistration(userData);<br>       <br>      },<br>    });<br>  }<br>async onModuleDestroy() {<br>    await this.consumer.disconnect();<br>  }<br>}</pre><ul><li><strong>Kafka Producer</strong>: Create a Kafka producer service that sends messages when users register.</li><li><strong>Kafka Consumer</strong>: Create a Kafka consumer service that listens for user registration messages and handles them accordingly.</li><li><strong>Integration</strong>: Inject Kafka producer in your user service to publish events.</li></ul><p>service-to-service communication via Kafka without creating full-blown microservices but keeping the decoupled architecture for scalability.</p><p><strong>To run code:</strong></p><pre>docker build -t my-nestjs-app<br>docker compose up<br>npm run start:dev<br>npx prisma studio </pre><pre>Received user registration event: {&quot;username&quot;:&quot;test&quot;,&quot;email&quot;:&quot;###&quot;,&quot;password_hash&quot;:&quot;####&quot;}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OeE0MYxhIZ0pbPNkkjonpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*8jLP2iDRhI9HTmvdRB3CwQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f752bc2c1323" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to setup multiple GitHub accounts on Ubuntu]]></title>
            <link>https://tamrakar-shreyaa.medium.com/how-to-setup-multiple-github-accounts-on-ubuntu-7e0f5983692f?source=rss-e6cf9555e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e0f5983692f</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[multi-account]]></category>
            <dc:creator><![CDATA[Tamrakar Shreyaa]]></dc:creator>
            <pubDate>Sat, 14 Sep 2024 14:45:16 GMT</pubDate>
            <atom:updated>2024-09-14T14:45:16.193Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*iakxWYgqiOUfUA4o1JnQRw.png" /></figure><p>Git is a crucial tool for version control in software development, enabling you to manage code changes across personal projects, open-source contributions, and collaborations within different organizations, making it essential to handle multiple Git user accounts effectively.</p><p><strong>Connecting</strong> <strong>your local environment to your GitHub accounts</strong></p><p>The concept is straightforward each GitHub account should have its own associated SSH key, which consists of a pair of public and private keys. The private key is stored locally on your machine, while the public key is added to your GitHub account. Therefore, the number of SSH keys you have corresponds to the number of GitHub accounts you use. For instance, with two GitHub accounts — a personal and a professional one — you’ll need two SSH keys (two private keys and two public keys).</p><p><strong>Check existing SSH keys on your local machine</strong></p><pre>ls -al ~/.ssh</pre><p>By default,</p><ul><li><em>id_rsa</em></li><li>id_rsa.pub</li></ul><p><strong>Create new SHH keys</strong></p><pre>ssh-keygen<br><br><br>Output<br>Generating public/private rsa key pair.<br>Enter file in which to save the key (/your_home/.ssh/id_rsa):offic</pre><p>for references</p><p><a href="https://www.digitalocean.com/community/tutorials/how-to-set-up-ssh-keys-on-ubuntu-20-04">How to Set Up SSH Keys on Ubuntu 20.04 | DigitalOcean</a></p><p><strong>Check Configuration File</strong></p><p>Inside the .ssh folder, create a file named config.</p><pre># Company Github Account<br>Host companyGit<br>    HostName github.com<br>    IdentityFile ~/.ssh/office-key<br>    User git<br>    IdentitiesOnly yes<br>    AddKeysToAgent yes<br><br># Personal Github Account<br>Host personalGit<br>    HostName github.com<br>    IdentityFile ~/.ssh/id_rsa<br>    User git<br>    IdentitiesOnly yes<br>    AddKeysToAgent yes</pre><p><strong>Creating a New Repository</strong></p><pre>#  For personal account<br>git remote add origin git@personalGit:personal-account-username/new-repo.git<br><br># For company account<br>git remote add origin git@companyGit:company-account-username/new-repo.git</pre><p><strong>Cloning an Existing Repository</strong></p><pre># For personal account<br>git clone git@personalGit:personal-account-username/existing-repo.git<br><br># For company account<br>git clone git@companyGit:company-account-username/existing-repo.git</pre><p><a href="https://tamrakar-shreyaa.medium.com/communication-with-the-database-via-rabbitmq-messages-in-a-laravel-microservice-application-484c58d55289">Communication with the database via RabbitMQ messages in a Laravel Microservice application</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e0f5983692f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Communication with the database via RabbitMQ messages in a Laravel Microservice application]]></title>
            <link>https://tamrakar-shreyaa.medium.com/communication-with-the-database-via-rabbitmq-messages-in-a-laravel-microservice-application-484c58d55289?source=rss-e6cf9555e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/484c58d55289</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[message-broker]]></category>
            <dc:creator><![CDATA[Tamrakar Shreyaa]]></dc:creator>
            <pubDate>Sun, 09 Jun 2024 03:51:23 GMT</pubDate>
            <atom:updated>2024-06-09T03:51:23.807Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-rV2rZCBGMNi2rVyOMe3Wg.png" /></figure><p><strong>Install RabbitMQ:</strong></p><p>Verify the installation and running status of RabbitMQ by consulting the earlier article I provided on how to install RabbitMQ.</p><p><a href="https://tamrakar-shreyaa.medium.com/install-rabbitmq-server-on-ubuntu-50fc58837bb1">Install RabbitMQ Server on Ubuntu</a></p><h3>Install Laravel Project</h3><p>Install Laravel on both the producer and consumer applications using Composer:</p><pre>composer create-project --prefer-dist laravel/laravel producer-app<br>composer create-project --prefer-dist laravel/laravel consumer-app</pre><h3>Install RabbitMQ PHP Library:</h3><p>In both Laravel applications, install the php-amqplib library to interact with RabbitMQ:</p><pre>composer require php-amqplib/php-amqplib</pre><h3>Producer and Consumer Application Configuration:</h3><p>Configure in both Laravel application to send messages to RabbitMQ. Update the .env file with RabbitMQ connection details:</p><pre>RABBITMQ_HOST=your_rabbitmq_host<br>RABBITMQ_PORT=5672<br>RABBITMQ_USER=your_rabbitmq_user<br>RABBITMQ_PASSWORD=your_rabbitmq_password<br>RABBITMQ_VHOST=your_rabbitmq_vhost</pre><p>Create a new RabbitMQ service class or use an existing one to handle message sending for <strong>Producer Laravel Application</strong>:</p><pre>&lt;?php<br><br>namespace App\Services;<br><br>use Illuminate\Support\Facades\Log;<br>use PhpAmqpLib\Connection\AMQPStreamConnection;<br>use PhpAmqpLib\Message\AMQPMessage;<br><br>class RabbitMQService<br>{<br>    private $connection;<br>    private $channel;<br><br>    public function __construct()<br>    {<br>        $this-&gt;connection = new AMQPStreamConnection(<br>            env(&#39;RABBITMQ_HOST&#39;),<br>            env(&#39;RABBITMQ_PORT&#39;),<br>            env(&#39;RABBITMQ_LOGIN&#39;),<br>            env(&#39;RABBITMQ_PASSWORD&#39;),<br>            env(&#39;RABBITMQ_VHOST&#39;)<br>        );<br><br>        $this-&gt;channel = $this-&gt;connection-&gt;channel();<br>    }<br><br><br>    public function userActivity($userId=&#39;1&#39;, $activity=&#39;order&#39;,$productId=&#39;123&#39;)<br>    {<br>      $this-&gt;channel-&gt;queue_declare(&#39;user_activity_queue&#39;, false, true, false, false);<br>    <br>        $messageBody = json_encode([&#39;user_id&#39; =&gt; $userId, &#39;activity&#39; =&gt; $activity,&#39;productId&#39;=&gt;$productId]);<br>        $message = new AMQPMessage($messageBody);<br>        Log::info($messageBody);<br><br>        $this-&gt;channel-&gt;basic_publish($message, &#39;&#39;, &#39;user_activity_queue&#39;);<br>    }<br><br>  <br><br>    public function __destruct()<br>    {<br>        $this-&gt;channel-&gt;close();<br>        $this-&gt;connection-&gt;close();<br>    }<br>}</pre><p>In your <strong>producer laravel application</strong>, use the RabbitMQ service to send messages:</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use App\Services\RabbitMQService;<br><br>class MessageController extends Controller<br>{<br><br>    public function userActivity()<br>    {<br>        $rabbitmqService = new RabbitMQService();<br>        $rabbitmqService-&gt;userActivity();<br>        return response()-&gt;json([&#39;message&#39; =&gt; &#39;Message sent successfully&#39;]);<br>    }<br>}</pre><p>Now let’s makes our required routes in routes/web.php</p><pre>use App\Http\Controllers\MessageController;<br>use Illuminate\Support\Facades\Route;<br><br>Route::get(&#39;/userActivity&#39;,[MessageController::class,&#39;userActivity&#39;]);</pre><h3>Consumer Application Configuration:</h3><p>Configure in consumer laravel application update the .env file with database connection details:</p><pre>DB_CONNECTION=mysql<br>DB_HOST=127.0.0.1<br>DB_PORT=3306<br>DB_DATABASE=consumer<br>DB_USERNAME=xxxxx<br>DB_PASSWORD=xxxxxx</pre><p><strong>Create Migration for Consumer Laravel Application</strong></p><pre>php artisan make:model Inventory -m</pre><p>Now In the <strong>Migration file</strong>,</p><pre>&lt;?php<br><br>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;<br><br>return new class extends Migration<br>{<br>    /**<br>     * Run the migrations.<br>     */<br>    public function up(): void<br>    {<br>        Schema::create(&#39;inventory&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;integer(&#39;productId&#39;);<br>            $table-&gt;integer(&#39;quantity&#39;);<br>            $table-&gt;timestamps();<br>        });<br>    }<br><br>    /**<br>     * Reverse the migrations.<br>     */<br>    public function down(): void<br>    {<br>        Schema::dropIfExists(&#39;table_inventory&#39;);<br>    }<br>};</pre><p>Next,this command use to in your terminal then this setup create to in your database.</p><pre>php artisan migrate</pre><p>The complete code in<strong> Inventory Model</strong> is given below.</p><pre>&lt;?php<br><br>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Factories\HasFactory;<br>use Illuminate\Database\Eloquent\Model;<br><br>class Inventory extends Model<br>{<br>    use HasFactory;<br><br>    protected $table=&quot;inventory&quot;;<br><br>}</pre><p>Create a new RabbitMQ service class or use an existing one to handle message sending for <strong>Consumer Laravel Application</strong>:</p><pre>&lt;?php<br><br>namespace App\Services;<br><br>use PhpAmqpLib\Connection\AMQPStreamConnection;<br><br>class RabbitMQService<br>{<br>    private $connection;<br>    private $channel;<br><br>    public function __construct()<br>    {<br>        $this-&gt;connection = new AMQPStreamConnection(<br>            env(&#39;RABBITMQ_HOST&#39;),<br>            env(&#39;RABBITMQ_PORT&#39;),<br>            env(&#39;RABBITMQ_LOGIN&#39;),<br>            env(&#39;RABBITMQ_PASSWORD&#39;),<br>            env(&#39;RABBITMQ_VHOST&#39;)<br>        );<br><br>        $this-&gt;channel = $this-&gt;connection-&gt;channel();<br>    }<br><br>    public function consumeUserActivity(string $queue)<br>    {<br>        Log::info(&#39;Consuming messages from queue: &#39; . $queue);<br><br>        $this-&gt;channel-&gt;queue_declare($queue, false, true, false, false);<br><br>        $callback = function ($message) {<br>            Log::info(&#39;Received message: &#39; . $message-&gt;body);<br><br>            // Process the message<br>            $data = json_decode($message-&gt;body, true);<br>            Log::info($data);<br><br>            $this-&gt;updateInventory($data[&#39;user_id&#39;], $data[&#39;activity&#39;], $data[&#39;productId&#39;]);<br><br>            // Acknowledge the message after processing<br>            if ($this-&gt;processingSuccessful()) {<br>                $message-&gt;ack();<br>                Log::info(&#39;Acknowledged message with delivery tag: &#39; . $message-&gt;delivery_info[&#39;delivery_tag&#39;]);<br>            } else {<br>                Log::error(&#39;Failed to process message. Rejecting message.&#39;);<br>                $message-&gt;reject(false); // Reject the message without requeueing<br>            }<br>        };<br><br>        $this-&gt;channel-&gt;basic_consume($queue, &#39;&#39;, false, false, false, false, $callback);<br><br>        while ($this-&gt;channel-&gt;is_consuming()) {<br>            $this-&gt;channel-&gt;wait();<br>        }<br>    }<br><br>    private function updateInventory($userId, $activity, $productId)<br>    {<br><br><br>        Log::info(&#39;qweqw&#39;);<br><br>        // Simulate updating inventory for user ID 1 buying a product<br>        $quantityToReduce = 1; // Assuming the user buys one product<br><br>        // Update inventory in the inventory database<br>        $inventory = Inventory::where(&#39;productId&#39;, $productId)-&gt;first();<br>        if ($inventory) {<br>            Log::info(&#39;inventory&#39;);<br>            $inventory-&gt;quantity -= $quantityToReduce;<br>            $inventory-&gt;save();<br>            // Log or perform any additional actions if needed<br>        } else {<br>            Log::info(&#39;issue&#39;);<br><br>            // Handle case where the product is not found in inventory<br>            // Log or perform any error handling as needed<br>        }<br>    }<br><br>    private function processingSuccessful()<br>    {<br>        // Implement your logic to check if message processing was successful<br>        // Return true if successful, false otherwise<br>        return true; // Change this as per your implementation<br>    }<br><br>    public function __destruct()<br>    {<br>        $this-&gt;channel-&gt;close();<br>        $this-&gt;connection-&gt;close();<br>    }<br>}</pre><p>Create an artisan command to consume user activity in <strong>consume laravel application</strong>:</p><pre>&lt;?php<br><br>namespace App\Console\Commands;<br><br><br>use App\Services\RabbitMQService;<br>use Illuminate\Console\Command;<br>use Illuminate\Support\Facades\Log;<br><br>class ConsumeUserActivity extends Command<br>{<br>    protected $signature = &#39;consume:useractivity&#39;;<br>    protected $description = &#39;Consume user activity messages from RabbitMQ&#39;;<br><br>    public function handle()<br>    {<br>        Log::info(&#39;handle&#39;);<br><br>        $rabbitmqService = new RabbitMQService();<br>        $rabbitmqService-&gt;consumeUserActivity(&#39;user_activity_queue&#39;, function ($message) {<br>            // Process the message here<br>            Log::info(&#39;message&#39;);<br><br>            $this-&gt;info(&quot;Received message: {$message-&gt;getBody()}&quot;);<br>        });<br>    <br>       <br>    }<br><br>  <br>}</pre><p>Run the consumer command to start listening for messages in <strong>consume laravel application</strong>:</p><pre>php artisan consume:useractivity</pre><h3>Output</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1aMAdKONvUx3q_eD7zWCfg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNh-x3nDuT2claHXWJsKxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*u9OYp-RrSBGuvi0S-kMtBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*SZdGiFSUsQOIS46qpczY5w.png" /></figure><p><a href="https://tamrakar-shreyaa.medium.com/implement-rabbitmq-messaging-between-two-laravel-2348a00a0805">Implement RabbitMQ Messaging Between Two Laravel</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=484c58d55289" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel horizon setup and implementation]]></title>
            <link>https://tamrakar-shreyaa.medium.com/laravel-horizon-setup-and-implementation-d883dab99907?source=rss-e6cf9555e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d883dab99907</guid>
            <category><![CDATA[laravel-11]]></category>
            <category><![CDATA[laravel-job]]></category>
            <category><![CDATA[laravel-events]]></category>
            <category><![CDATA[laravel-horizon]]></category>
            <category><![CDATA[laravel-queue]]></category>
            <dc:creator><![CDATA[Tamrakar Shreyaa]]></dc:creator>
            <pubDate>Tue, 21 May 2024 10:06:04 GMT</pubDate>
            <atom:updated>2024-05-21T10:06:04.939Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3rMEGAx7SWF50EM_m84W9Q.jpeg" /></figure><p>Laravel Horizon presents a visually appealing dashboard and enables code-driven configuration for managing Redis queues in Laravel applications. It serves as a robust management and monitoring tool, specifically crafted to streamline background job processing. By acting as a centralized hub, it provides developers with insights and control over job execution.</p><p><strong>Real-time Monitoring:</strong> With Laravel Horizon, you get access to a visually pleasing, real-time dashboard, providing immediate insights into background job processing. This facilitates swift issue identification and proactive monitoring for optimal performance.</p><p><strong>Task Metrics:</strong> Laravel Horizon offers detailed metrics to deepen your understanding of your application’s job queue. It provides valuable data on job execution times, success rates, and failure details, essential for fine-tuning and optimizing background tasks.</p><p><strong>Effortless Scaling:</strong> Horizon simplifies the scaling process for Laravel applications, ensuring seamless handling of workload spikes or varying intensities without compromising performance or responsiveness.</p><p><strong>Job Retry Management:</strong> Laravel Horizon streamlines the management of failed jobs through an intuitive interface. It allows for easy retrying of failed jobs, minimizing the impact of errors and aiding effective error resolution for a more resilient job processing system.</p><p><strong>Intuitive Configuration:</strong> Laravel Horizon features an easy-to-configure setup, empowering developers to tailor the tool to their project’s specific requirements. Its intuitive configuration options enable customization of features to suit the unique needs of Laravel applications, ultimately enhancing development efficiency.</p><h3>Install Laravel Project</h3><p>Run the command to induct fresh Laravel project.</p><pre>composer create-project laravel/laravel laravel-horizon</pre><h3>Install laravel horizon Library:</h3><pre>composer require laravel/horizon<br><br>php artisan horizon:install</pre><p>It will install the horizon on your project. Now you can able to see the list of the horizon commands on php artisan.</p><p>Now, you need to install Redis. To install Redis, run the following command</p><pre>composer require predis/predis</pre><h3>Setting up DB</h3><pre># DB Section<br>DB_CONNECTION=mysql<br>DB_HOST=127.0.0.1<br>DB_PORT=3306<br>DB_DATABASE=databasename<br>DB_USERNAME=root<br>DB_PASSWORD=password<br><br># Session section<br>QUEUE_CONNECTION=redis<br>REDIS_CLIENT=predis<br><br># email<br><br>MAIL_DRIVER=smtp<br>MAIL_HOST=smtp.mailtrap.io<br>MAIL_PORT=2525<br>MAIL_USERNAME=your_mailtrap_username<br>MAIL_PASSWORD=your_mailtrap_password<br>MAIL_ENCRYPTION=tls</pre><h3>Set up an email job</h3><pre>php artisan make:job SendEmail</pre><p>This will create a new job file in the <em>app/Jobs</em> directory, named <em>SendEmail.php</em>.</p><pre>&lt;?php<br><br>namespace App\Jobs;<br><br>use App\Mail\WelcomeEmail;<br>use Illuminate\Bus\Queueable;<br>use Illuminate\Contracts\Queue\ShouldQueue;<br>use Illuminate\Foundation\Bus\Dispatchable;<br>use Illuminate\Queue\InteractsWithQueue;<br>use Illuminate\Queue\SerializesModels;<br>use Illuminate\Support\Facades\Mail;<br>use Resend\Laravel\Facades\Resend;<br><br>class SendEmail implements ShouldQueue<br>{<br>    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;<br><br>    protected $email;<br><br>    /**<br>     * Create a new job instance.<br>     */<br>    public function __construct()<br>    {<br><br>    }<br><br>    /**<br>     * Execute the job.<br>     */<br>    public function handle()<br>    {<br>      Mail::to(&#39;test@gmail.com&#39;)-&gt;send(new WelcomeEmail());<br>    }<br>}</pre><pre>php artisan make:Mail WelcomeEmail</pre><p>This will create a new mail file in the <em>app/Ma</em>il directory, named WelcomeEmail<em>.php</em>.</p><pre>&lt;?php<br><br>namespace App\Mail;<br><br>use Illuminate\Bus\Queueable;<br>use Illuminate\Contracts\Queue\ShouldQueue;<br>use Illuminate\Mail\Mailable;<br>use Illuminate\Mail\Mailables\Content;<br>use Illuminate\Mail\Mailables\Envelope;<br>use Illuminate\Queue\SerializesModels;<br><br>class WelcomeEmail extends Mailable<br>{<br>    use Queueable, SerializesModels;<br><br>    /**<br>     * Create a new message instance.<br>     */<br>    public function __construct()<br>    {<br>        //<br>    }<br><br>    /**<br>     * Get the message envelope.<br>     */<br>    public function envelope(): Envelope<br>    {<br>        return new Envelope(<br>            subject: &#39;Welcome Email&#39;,<br>        );<br>    }<br><br>    /**<br>     * Get the message content definition.<br>     */<br>    public function content(): Content<br>    {<br>        return new Content(<br>            view: &#39;emails.demo&#39;,<br>        );<br>    }<br><br>    /**<br>     * Get the attachments for the message.<br>     *<br>     * @return array&lt;int, \Illuminate\Mail\Mailables\Attachment&gt;<br>     */<br>    public function attachments(): array<br>    {<br>        return [];<br>    }<br>}</pre><p>create a new blade file in the <em>views/</em>emails directory, named <em>demo.blade.php</em>.</p><pre>&lt;h1&gt;this is mail templete&lt;/h1&gt;</pre><p>create a new controller file in the App\Http\Controllers directory, named EmailController.php</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use App\Jobs\SendEmail;<br><br>class EmailController extends Controller<br>{<br>    public function send()<br>    {<br>        SendEmail::dispatch()-&gt;onQueue(&#39;emails&#39;);<br>        return &quot;Email queued for sending!&quot;;<br>    }<br>}</pre><p>Now let’s makes our required routes in routes/web.php</p><pre>&lt;?php<br><br>use App\Http\Controllers\EmailController;<br>use Illuminate\Support\Facades\Route;<br><br><br>Route::get(&#39;/demo&#39;,[EmailController::class,&#39;send&#39;])-&gt;name(&#39;demo&#39;);</pre><h3>To access the horizon</h3><pre>http://127.0.0.1:8000/horizon</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*55ySgNLcA8cU-3R93kX7TA.png" /></figure><h3>To run horizon</h3><pre>php artisan horizon<br><br>#to check status<br>php artisan horizon:status</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5umMVDUZ67CEcX7GsHjyJg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w2dQsa9wPLfgmp4bynYiIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jkxKD1vrRyyNqw8Oi1kVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fPkM1ORIG-oqHM7BByhLhA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d883dab99907" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>