<?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 Moise rushanika on Medium]]></title>
        <description><![CDATA[Stories by Moise rushanika on Medium]]></description>
        <link>https://medium.com/@moiserushanika2006?source=rss-8dd0bd4ca9c9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oG4lSNohI61b7vNGLTgCeA@2x.jpeg</url>
            <title>Stories by Moise rushanika on Medium</title>
            <link>https://medium.com/@moiserushanika2006?source=rss-8dd0bd4ca9c9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 07:49:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@moiserushanika2006/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[Domain-Driven Design: Simplifying Software Through Domain Modeling]]></title>
            <link>https://towardsdev.com/domain-driven-design-simplifying-software-through-domain-modeling-b9e7df3bc733?source=rss-8dd0bd4ca9c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9e7df3bc733</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[design-process]]></category>
            <dc:creator><![CDATA[Moise rushanika]]></dc:creator>
            <pubDate>Mon, 16 Dec 2024 11:32:18 GMT</pubDate>
            <atom:updated>2024-12-16T14:20:10.819Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vGz70ghQTtjqO3ieW4DWow.jpeg" /></figure><p>In software development, <strong>Domain-Driven Design (DDD)</strong> provides a framework to align software development with complex business needs. Introduced by Eric Evans, DDD emphasizes collaboration between domain experts and developers, leveraging domain models to design systems that truly represent business processes.</p><p>Let’s delve into the key principles of DDD, using practical examples in JavaScript to illustrate how these concepts can be applied in real-world scenarios.</p><h3>Unified Language</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*3lAqYqhfBQSXnIp8BeqbGA.png" /></figure><p><strong>Unified Language</strong>, or the “Ubiquitous Language,” is central to DDD. It is a shared language developed by both technical and non-technical stakeholders to avoid misunderstandings. This language drives the creation of the domain model.<br>Imagine you’re building a library management system. Key terms like “Book,” “Member,” “Borrow,” and “Return” become part of your ubiquitous language. These terms are reflected in your code:</p><pre>class Book {<br>  constructor(title, author, isbn) {<br>    this.title = title;<br>    this.author = author;<br>    this.isbn = isbn;<br>  }<br>}<br><br>class Member {<br>  constructor(name, membershipId) {<br>    this.name = name;<br>    this.membershipId = membershipId;<br>  }<br><br>  borrow(book) {<br>    console.log(`${this.name} has borrowed &quot;${book.title}&quot;.`);<br>  }<br>}</pre><p>Here, <strong>Book</strong> and <strong>Member</strong> represent real-world entities, and their behavior reflects domain knowledge.</p><h3>Business Entities</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*s-ZRJfPdZavzPva5ke_6zg.png" /></figure><p>Business entities encapsulate critical business concepts and logic. These entities often have unique identities and represent tangible or conceptual objects in the system.<br>In an e-commerce system, entities like <strong>Product</strong> and <strong>Order</strong> are modeled with behaviors and attributes:</p><pre>class Product {<br>  constructor(id, name, price) {<br>    this.id = id;<br>    this.name = name;<br>    this.price = price;<br>  }<br>}<br><br>class Order {<br>  constructor(orderId) {<br>    this.orderId = orderId;<br>    this.items = [];<br>  }<br><br>  addItem(product, quantity) {<br>    this.items.push({ product, quantity });<br>  }<br><br>  calculateTotal() {<br>    return this.items.reduce(<br>      (total, item) =&gt; total + item.product.price * item.quantity,<br>      0<br>    );<br>  }<br>}<br><br>const product = new Product(1, &quot;Laptop&quot;, 1200);<br>const order = new Order(101);<br>order.addItem(product, 2);<br>console.log(order.calculateTotal()); // Output: 2400</pre><h3>Model Boundaries</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*LIj0xSBY12gfmigrLex7pw.png" /></figure><p>Model boundaries help ensure clarity and consistency within a domain. <strong>Bounded Contexts</strong> are a key concept here, defining clear boundaries for a domain model and its associated logic.<br>In a large system, separate contexts for billing and shipping prevent overlapping logic:</p><pre>// Billing context<br>class Invoice {<br>  constructor(invoiceId, amount) {<br>    this.invoiceId = invoiceId;<br>    this.amount = amount;<br>  }<br><br>  generate() {<br>    console.log(`Invoice #${this.invoiceId} for $${this.amount} generated.`);<br>  }<br>}<br><br>// Shipping context<br>class Shipping {<br>  constructor(orderId, address) {<br>    this.orderId = orderId;<br>    this.address = address;<br>  }<br><br>  dispatch() {<br>    console.log(`Order #${this.orderId} is being shipped to ${this.address}.`);<br>  }<br>}</pre><p>These contexts operate independently, but integrations can occur via APIs or shared events.</p><h3>Aggregation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*YI94abvLQLgxjbNzVmoNSA.png" /></figure><p>An <strong>Aggregate</strong> groups related entities and ensures consistency within a boundary. Changes to entities within an aggregate are managed through a single entry point the <strong>Aggregate Root</strong>.<br>In a banking application, an <strong>Account</strong> aggregate may encapsulate transactions</p><pre>class Account {<br>  constructor(accountNumber, balance = 0) {<br>    this.accountNumber = accountNumber;<br>    this.balance = balance;<br>    this.transactions = [];<br>  }<br><br>  deposit(amount) {<br>    this.balance += amount;<br>    this.transactions.push({ type: &quot;deposit&quot;, amount });<br>  }<br><br>  withdraw(amount) {<br>    if (this.balance &lt; amount) {<br>      throw new Error(&quot;Insufficient funds.&quot;);<br>    }<br>    this.balance -= amount;<br>    this.transactions.push({ type: &quot;withdrawal&quot;, amount });<br>  }<br><br>  getBalance() {<br>    return this.balance;<br>  }<br>}</pre><p>Here, <strong>Account</strong> is the aggregate root managing <strong>Transaction</strong> entities.</p><h3>Entities vs. Value Objects</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*vVOm1LKP8BgyP57iAT664w.png" /></figure><p>Entities have unique identities, while <strong>Value Objects</strong> are immutable and identified by their attributes rather than an ID.</p><p>In a food delivery app, an <strong>Address</strong> could be modeled as a value object:</p><pre>class Address {<br>  constructor(street, city, zipCode) {<br>    this.street = street;<br>    this.city = city;<br>    this.zipCode = zipCode;<br>  }<br>}<br><br>class Restaurant {<br>  constructor(name, address) {<br>    this.name = name;<br>    this.address = address; // Value object<br>  }<br>}<br><br>const address = new Address(&quot;123 Main St&quot;, &quot;Springfield&quot;, &quot;12345&quot;);<br>const restaurant = new Restaurant(&quot;Pizza Place&quot;, address);<br><br>console.log(restaurant.address.city); // Output: Springfield</pre><p>Changes to the <strong>Address</strong> create a new instance, ensuring immutability.</p><h3>Operational Modeling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*O7M0vZmqDMZoxbZh-jcWDA.png" /></figure><p>Operational objects, such as <strong>Repositories</strong> and <strong>Services</strong>, handle domain logic outside entities and aggregates.<br>A <strong>UserService</strong> manages user-related operations:</p><pre>class UserService {<br>  constructor(userRepository) {<br>    this.userRepository = userRepository;<br>  }<br><br>  registerUser(name, email) {<br>    const user = { id: Date.now(), name, email };<br>    this.userRepository.save(user);<br>    return user;<br>  }<br>}<br><br>class UserRepository {<br>  constructor() {<br>    this.users = [];<br>  }<br><br>  save(user) {<br>    this.users.push(user);<br>  }<br><br>  findByEmail(email) {<br>    return this.users.find((u) =&gt; u.email === email);<br>  }<br>}<br><br>const userRepository = new UserRepository();<br>const userService = new UserService(userRepository);<br>userService.registerUser(&quot;John Doe&quot;, &quot;john@example.com&quot;);<br>console.log(userRepository.findByEmail(&quot;john@example.com&quot;));</pre><h3>Layering the Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*Y8iEOzpntEyr3iyU11y13A.png" /></figure><p>DDD emphasizes organizing code into layers to manage complexity. Common layers include <strong>Domain</strong>, <strong>Application</strong>, and <strong>Infrastructure</strong>.</p><p><strong>Example</strong>:<br>For a blog platform:</p><ul><li><strong>Domain Layer</strong>: Models like Post and Comment.</li><li><strong>Application Layer</strong>: Services like PostService.</li><li><strong>Infrastructure Layer</strong>: Repositories and external integrations.</li></ul><h3>Building the Domain Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*xWA-MSZwT1yjLIqIi_u8tw.png" /></figure><p>To build a domain model, extract key concepts through collaboration with domain experts and iterative refinement. Use tools like UML diagrams, user stories, and prototypes.</p><h3>Conclusion</h3><p>Domain-Driven Design ensures software reflects real-world business processes. By employing entities, value objects, aggregates, and operational models, developers can create robust, scalable systems. Through layering and clear boundaries, complexity is reduced, paving the way for innovation. Applying DDD concepts in JavaScript demonstrates its adaptability and power, even in small projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9e7df3bc733" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/domain-driven-design-simplifying-software-through-domain-modeling-b9e7df3bc733">Domain-Driven Design: Simplifying Software Through Domain Modeling</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Multithreading Design Patterns]]></title>
            <link>https://towardsdev.com/mastering-multithreading-design-patterns-e4cf7840fcec?source=rss-8dd0bd4ca9c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4cf7840fcec</guid>
            <dc:creator><![CDATA[Moise rushanika]]></dc:creator>
            <pubDate>Sat, 14 Dec 2024 11:12:40 GMT</pubDate>
            <atom:updated>2024-12-16T14:31:19.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*mvN5-McZMIMmYgSNrHMLvg.png" /></figure><p>Multithreading is a powerful concept in software engineering that allows a program to execute multiple tasks concurrently within the same process. Threads are lightweight units of execution that share a process&#39;s resources, such as memory space. While multithreading enhances performance and responsiveness, it introduces complexities like synchronization, communication, and potential race conditions. To address these challenges, developers rely on well-defined multithreading design patterns.</p><p>This article delves into key multithreading design patterns, their uses, and real-world applications.</p><h3>1. Producer-Consumer Pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*6oBfa4h-esS4XFbRglRPvw.png" /></figure><p>The Producer-Consumer pattern involves two types of threads: producers that generate data and consumers that process the data. A blocking queue serves as a buffer between the two, ensuring that producers and consumers operate independently.</p><p><strong>Scenario:</strong> A logging system where multiple threads log messages (producers) and a dedicated thread writes these messages to a file (consumer).</p><pre>class BlockingQueue {<br>  constructor() {<br>    this.queue = [];<br>    this.resolve = null;<br>  }<br><br>  enqueue(item) {<br>    this.queue.push(item);<br>    if (this.resolve) {<br>      this.resolve(this.queue.shift());<br>      this.resolve = null;<br>    }<br>  }<br><br>  async dequeue() {<br>    if (this.queue.length &gt; 0) {<br>      return this.queue.shift();<br>    }<br>    return new Promise((resolve) =&gt; (this.resolve = resolve));<br>  }<br>}<br><br>// Producers and consumers<br>const queue = new BlockingQueue();<br><br>async function producer() {<br>  for (let i = 0; i &lt; 5; i++) {<br>    console.log(`Producing: File ${i}`);<br>    queue.enqueue(`File ${i}`);<br>    await new Promise((resolve) =&gt; setTimeout(resolve, 1000)); // Simulate delay<br>  }<br>  queue.enqueue(null); // Signal the end<br>}<br><br>async function consumer() {<br>  while (true) {<br>    const item = await queue.dequeue();<br>    if (!item) break; // End signal<br>    console.log(`Processing: ${item}`);<br>    await new Promise((resolve) =&gt; setTimeout(resolve, 1500)); // Simulate delay<br>  }<br>}<br><br>// Run the producer and consumer<br>producer();<br>consumer();</pre><h3>2. Thread Pool Pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*A9B0oEXfKXDucRrWLZ8_Gg.png" /></figure><p>The Thread Pool pattern pre-creates worker threads to handle tasks, avoiding the overhead of repeatedly creating and destroying threads. <strong>Web Workers</strong> are ideal for JavaScript.</p><p><strong>Scenario:</strong> A video-processing application with multiple simultaneous jobs.</p><pre>class ThreadPool {<br>  constructor(size) {<br>    this.pool = [];<br>    this.queue = [];<br>    for (let i = 0; i &lt; size; i++) {<br>      this.pool.push(new Worker(&quot;worker.js&quot;));<br>    }<br>  }<br><br>  run(task) {<br>    return new Promise((resolve, reject) =&gt; {<br>      const worker = this.pool.pop();<br>      if (worker) {<br>        worker.onmessage = (e) =&gt; {<br>          resolve(e.data);<br>          this.pool.push(worker);<br>          if (this.queue.length) {<br>            this.run(this.queue.shift());<br>          }<br>        };<br>        worker.onerror = reject;<br>        worker.postMessage(task);<br>      } else {<br>        this.queue.push(task);<br>      }<br>    });<br>  }<br>}<br><br>// worker.js<br>self.onmessage = (e) =&gt; {<br>  const result = e.data * 2; // Simulate heavy computation<br>  self.postMessage(result);<br>};<br><br>// Main thread<br>const pool = new ThreadPool(2);<br>pool.run(10).then(console.log); // Output: 20<br>pool.run(20).then(console.log); // Output: 40</pre><h3>3. Futures and Promises Pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*Fkm6lT7qzgQ8SCUakmxFuQ.png" /></figure><p>This pattern separates the creation of a task and the retrieval of its result. A promise object holds the task&#39;s eventual result, while a future provides a way to access the result.</p><p><strong>Scenario:</strong> Fetching data from multiple APIs concurrently without blocking the main thread.</p><pre>async function fetchData(apiUrl) {<br>  return new Promise((resolve) =&gt; {<br>    setTimeout(() =&gt; resolve(`Data from ${apiUrl}`), 2000); // Simulate delay<br>  });<br>}<br><br>async function main() {<br>  const promises = [<br>    fetchData(&quot;https://api.example.com/1&quot;),<br>    fetchData(&quot;https://api.example.com/2&quot;),<br>  ];<br>  const results = await Promise.all(promises);<br>  console.log(results); // Output: [&#39;Data from ...&#39;, &#39;Data from ...&#39;]<br>}<br><br>main();</pre><h3>4. Monitor Object Pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*QrearrfrecDzU_3aNB2Cyg.png" /></figure><p>The Monitor Object pattern ensures safe access to shared resources by multiple threads. Although JavaScript uses the event loop, <strong>locks</strong> can simulate this behavior.</p><p><strong>Scenario:</strong> Managing access to a shared counter.</p><pre>class Monitor {<br>  constructor() {<br>    this.locked = false;<br>  }<br><br>  async lock() {<br>    while (this.locked) {<br>      await new Promise((resolve) =&gt; setTimeout(resolve, 100)); // Wait for unlock<br>    }<br>    this.locked = true;<br>  }<br><br>  unlock() {<br>    this.locked = false;<br>  }<br>}<br><br>// Shared counter<br>const monitor = new Monitor();<br>let counter = 0;<br><br>async function increment() {<br>  await monitor.lock();<br>  const temp = counter;<br>  await new Promise((resolve) =&gt; setTimeout(resolve, 500)); // Simulate delay<br>  counter = temp + 1;<br>  monitor.unlock();<br>  console.log(`Counter: ${counter}`);<br>}<br><br>increment();<br>increment();</pre><h3>5. Barrier Pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*Oi89ympdwDh4q7sOF7AAzA.png" /></figure><p>The Barrier pattern synchronizes threads, making them wait until all have reached a certain point before continuing.</p><p><strong>Scenario:</strong> Synchronizing multiple tasks in a data pipeline.</p><pre>class Barrier {<br>  constructor(count) {<br>    this.count = count;<br>    this.waiting = 0;<br>    this.resolve = null;<br>  }<br><br>  async wait() {<br>    this.waiting++;<br>    if (this.waiting === this.count) {<br>      this.resolve();<br>    }<br>    return new Promise((resolve) =&gt; {<br>      if (this.waiting === this.count) {<br>        this.waiting = 0;<br>        resolve();<br>      } else {<br>        this.resolve = resolve;<br>      }<br>    });<br>  }<br>}<br><br>const barrier = new Barrier(3);<br><br>async function task(id) {<br>  console.log(`Task ${id} started`);<br>  await new Promise((resolve) =&gt; setTimeout(resolve, 1000)); // Simulate work<br>  console.log(`Task ${id} waiting`);<br>  await barrier.wait();<br>  console.log(`Task ${id} completed`);<br>}<br><br>task(1);<br>task(2);<br>task(3);</pre><h3>6. Read-Write Lock Pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*pwomKM8vPTLRro8qjp8wZw.png" /></figure><p>This pattern allows multiple threads to read a resource but only one to write to, ensuring data consistency.</p><p><strong>Scenario:</strong> A shared cache with frequent reads and occasional writes.</p><pre>class ReadWriteLock {<br>  constructor() {<br>    this.readers = 0;<br>    this.writeLock = false;<br>  }<br><br>  async readLock() {<br>    while (this.writeLock) {<br>      await new Promise((resolve) =&gt; setTimeout(resolve, 100));<br>    }<br>    this.readers++;<br>  }<br><br>  readUnlock() {<br>    this.readers--;<br>  }<br><br>  async writeLock() {<br>    while (this.writeLock || this.readers &gt; 0) {<br>      await new Promise((resolve) =&gt; setTimeout(resolve, 100));<br>    }<br>    this.writeLock = true;<br>  }<br><br>  writeUnlock() {<br>    this.writeLock = false;<br>  }<br>}<br><br>// Usage example<br>const lock = new ReadWriteLock();<br>let sharedData = 0;<br><br>async function readTask() {<br>  await lock.readLock();<br>  console.log(`Read: ${sharedData}`);<br>  lock.readUnlock();<br>}<br><br>async function writeTask() {<br>  await lock.writeLock();<br>  sharedData++;<br>  console.log(`Write: ${sharedData}`);<br>  lock.writeUnlock();<br>}<br><br>readTask();<br>writeTask();<br>readTask();</pre><h3>Conclusion</h3><p>Multithreading design patterns, while simulated, provide powerful solutions for managing concurrency in complex applications. By leveraging these patterns, developers can build efficient, reliable, and scalable systems that handle real-world challenges effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4cf7840fcec" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/mastering-multithreading-design-patterns-e4cf7840fcec">Mastering Multithreading Design Patterns</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Smarter Job Matching Systems with AI: NestJS, Pinecone, MongoDB, and OpenAI in Action]]></title>
            <link>https://blog.stackademic.com/building-smarter-job-matching-systems-with-ai-nestjs-pinecone-mongodb-and-openai-in-action-7b9139e6bc49?source=rss-8dd0bd4ca9c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b9139e6bc49</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[pinecone]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Moise rushanika]]></dc:creator>
            <pubDate>Mon, 25 Nov 2024 23:59:35 GMT</pubDate>
            <atom:updated>2024-11-27T19:47:52.663Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*2Uj9CypVAVT2IkjFRa8Nag.jpeg" /></figure><p>AI job matching leverages advanced technologies like machine learning, natural language processing, and vector databases to connect job seekers with relevant opportunities. In this article, we’ll explore how a system built with <strong>NestJS</strong>, <strong>Pinecone VectorDB</strong>, <strong>MongoDB</strong>, and <strong>OpenAI</strong> can efficiently perform this task. We’ll also include code examples to illustrate the implementation.</p><p><strong>System Architecture Overview</strong></p><p>Components:</p><ol><li><strong>NestJS</strong>: Backend framework for handling APIs and business logic.</li><li><strong>MongoDB</strong>: Stores candidate and job data in a structured format.</li><li><strong>Pinecone VectorDB</strong>: Used for semantic similarity search between candidate profiles and job descriptions.</li><li><strong>OpenAI</strong>: Generates vector embeddings for semantic understanding of text.</li></ol><h3>Workflow:</h3><ol><li>Candidate information and job postings are stored in MongoDB.</li><li>OpenAI converts the textual descriptions into vector embeddings.</li><li>These embeddings are stored in Pinecone for fast similarity search.</li><li>When a new job or candidate is added, the system matches them using semantic similarity.</li></ol><h3>What Is Similarity Search?</h3><p>Similarity search identifies items (e.g., resumes or job descriptions) that are semantically close to a given query. This is crucial for AI job matching as it focuses on <strong>meaning</strong> rather than exact keyword matches.</p><h3>How It Works:</h3><ol><li><strong>Text Vectorization</strong>: Converts text into high-dimensional vector representations, capturing semantic meaning.</li><li><strong>Storage in Vector Database</strong>: Stores embeddings in a database optimized for similarity queries, like Pinecone.</li><li><strong>Query Matching</strong>: Matches new vectors (e.g., job descriptions) against stored vectors (e.g., candidate resumes) using similarity metrics like <strong>cosine similarity</strong> or <strong>Euclidean distance</strong>.</li></ol><h3>Why Similarity Search Matters</h3><ul><li><strong>Contextual Understanding</strong>: Captures the meaning behind words, not just their literal appearance.</li><li><strong>Scalability</strong>: Efficiently handles millions of candidates and jobs.</li><li><strong>Improved Results</strong>: Finds relevant matches even when keywords differ.</li></ul><p>For instance, a job requiring “frontend development” could match a resume mentioning “React and UI/UX design” due to semantic similarity.</p><h3>Implementation</h3><h4>1. Setting Up NestJS</h4><p>Install dependencies for NestJS, MongoDB, and Pinecone:</p><pre>npm install @nestjs/common @nestjs/core @nestjs/mongoose mongoose pinecone-client @nestjs/config openai</pre><p>Create a module for managing candidates and jobs.</p><p><strong>2. Define MongoDB Schemas</strong></p><pre>// schemas/candidate.schema.ts<br>import { Prop, Schema, SchemaFactory } from &#39;@nestjs/mongoose&#39;;<br>import { Document } from &#39;mongoose&#39;;<br><br>@Schema()<br>export class Candidate extends Document {<br>  @Prop({ required: true })<br>  name: string;<br><br>  @Prop({ required: true })<br>  skills: string[];<br><br>  @Prop({ required: true })<br>  resume: string; // Plain text of the resume<br>}<br><br>export const CandidateSchema = SchemaFactory.createForClass(Candidate);<br><br>// schemas/job.schema.ts<br>@Schema()<br>export class Job extends Document {<br>  @Prop({ required: true })<br>  title: string;<br><br>  @Prop({ required: true })<br>  description: string;<br><br>  @Prop({ required: true })<br>  skillsRequired: string[];<br>}<br><br>export const JobSchema = SchemaFactory.createForClass(Job);</pre><h4>3. Connect OpenAI for Embedding Generation</h4><p>Install the OpenAI SDK and configure it:</p><pre>import { Configuration, OpenAIApi } from &#39;openai&#39;;<br><br>const configuration = new Configuration({<br>  apiKey: process.env.OPENAI_API_KEY,<br>});<br>const openai = new OpenAIApi(configuration);<br><br>export const generateEmbedding = async (text: string): Promise&lt;number[]&gt; =&gt; {<br>  const response = await openai.createEmbedding({<br>    model: &#39;text-embedding-ada-002&#39;,<br>    input: text,<br>  });<br>  return response.data.data[0].embedding;<br>};</pre><h4>4. Store and Search Vectors in Pinecone</h4><p>Initialize the Pinecone client and handle embeddings:</p><pre>import { PineconeClient } from &#39;pinecone-client&#39;;<br><br>const pinecone = new PineconeClient();<br>await pinecone.init({<br>  apiKey: process.env.PINECONE_API_KEY,<br>  environment: process.env.PINECONE_ENV,<br>});<br><br>const index = pinecone.Index(&#39;job-matching&#39;);<br><br>export const upsertEmbedding = async (id: string, embedding: number[]) =&gt; {<br>  await index.upsert([{ id, values: embedding }]);<br>};<br><br>export const searchEmbedding = async (embedding: number[]) =&gt; {<br>  const result = await index.query({<br>    vector: embedding,<br>    topK: 5, // Return top 5 matches<br>    includeMetadata: true,<br>  });<br>  return result.matches;<br>};</pre><h4>5. Services for Job Matching</h4><p>Define services to handle candidates and jobs.</p><h4>Candidate Service</h4><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { InjectModel } from &#39;@nestjs/mongoose&#39;;<br>import { Model } from &#39;mongoose&#39;;<br>import { Candidate } from &#39;./schemas/candidate.schema&#39;;<br>import { generateEmbedding, upsertEmbedding } from &#39;./pinecone.service&#39;;<br><br>@Injectable()<br>export class CandidateService {<br>  constructor(@InjectModel(Candidate.name) private candidateModel: Model&lt;Candidate&gt;) {}<br><br>  async addCandidate(candidateData: Partial&lt;Candidate&gt;) {<br>    const candidate = new this.candidateModel(candidateData);<br>    await candidate.save();<br><br>    const embedding = await generateEmbedding(candidate.resume);<br>    await upsertEmbedding(candidate._id.toString(), embedding);<br><br>    return candidate;<br>  }<br>}</pre><p><strong>Job Service</strong></p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { InjectModel } from &#39;@nestjs/mongoose&#39;;<br>import { Model } from &#39;mongoose&#39;;<br>import { Job } from &#39;./schemas/job.schema&#39;;<br>import { generateEmbedding, searchEmbedding } from &#39;./pinecone.service&#39;;<br><br>@Injectable()<br>export class JobService {<br>  constructor(@InjectModel(Job.name) private jobModel: Model&lt;Job&gt;) {}<br><br>  async findMatchingCandidates(jobId: string) {<br>    const job = await this.jobModel.findById(jobId);<br>    if (!job) throw new Error(&#39;Job not found&#39;);<br><br>    const jobEmbedding = await generateEmbedding(job.description);<br>    const matches = await searchEmbedding(jobEmbedding);<br><br>    return matches.map((match) =&gt; match.metadata); // Return candidate info<br>  }<br>}</pre><h4>6. Controllers</h4><p>Define routes for adding candidates and finding matches.</p><pre>import { Controller, Post, Body, Param, Get } from &#39;@nestjs/common&#39;;<br>import { CandidateService } from &#39;./candidate.service&#39;;<br>import { JobService } from &#39;./job.service&#39;;<br><br>@Controller(&#39;candidates&#39;)<br>export class CandidateController {<br>  constructor(private candidateService: CandidateService) {}<br><br>  @Post()<br>  async addCandidate(@Body() candidateData: any) {<br>    return this.candidateService.addCandidate(candidateData);<br>  }<br>}<br><br>@Controller(&#39;jobs&#39;)<br>export class JobController {<br>  constructor(private jobService: JobService) {}<br><br>  @Get(&#39;:id/matches&#39;)<br>  async findMatches(@Param(&#39;id&#39;) id: string) {<br>    return this.jobService.findMatchingCandidates(id);<br>  }<br>}</pre><h4>7. Testing the System</h4><ol><li>Add a candidate using a POST request:</li></ol><pre>{<br>  &quot;name&quot;: &quot;Moise Rush&quot;,<br>  &quot;skills&quot;: [&quot;JavaScript&quot;, &quot;React&quot;, &quot;Nestjs&quot;, &quot;Next&quot;],<br>  &quot;resume&quot;: &quot;Experienced full-stack developer with expertise in JavaScript, Nestjs, and Node.js...&quot;<br>}</pre><p>2. Add a job using another POST request:</p><pre>{<br>  &quot;title&quot;: &quot;Frontend Developer&quot;,<br>  &quot;description&quot;: &quot;Looking for a frontend developer proficient in React and JavaScript...&quot;,<br>  &quot;skillsRequired&quot;: [&quot;Nestjs&quot;, &quot;React&quot;, &quot;JavaScript&quot;]<br>}</pre><p>3. Fetch matches for the job:</p><pre>GET /jobs/:id/matches</pre><h3>Real-World Impact</h3><p>Using similarity search ensures:</p><ul><li>Better contextual matches (e.g., synonyms and related concepts).</li><li>Higher relevance between candidates and jobs.</li><li>Scalability for large datasets with fast retrieval.</li></ul><p>For example:</p><ul><li>Job: “Frontend Developer”</li><li>Candidate Matches:</li></ul><ol><li>Candidate A (Score: <strong>0.95</strong>): “React, JavaScript”</li><li>Candidate B (Score: <strong>0.85</strong>): “React, CSS”</li><li>Candidate C (Score: <strong>0.30</strong>): “Python, Django”</li></ol><p>This approach allows recruiters to focus on the most relevant candidates instantly.</p><h3>Conclusion</h3><p>This system enables efficient AI-driven job matching by integrating <strong>NestJS</strong>, <strong>MongoDB</strong>, <strong>Pinecone</strong>, and <strong>OpenAI</strong>. MongoDB stores structured data, OpenAI generates embeddings, Pinecone performs similarity searches, and NestJS ties it together with a clean API.</p><p>This highly scalable architecture makes it ideal for platforms with growing datasets and increasing matching complexity.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b9139e6bc49" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/building-smarter-job-matching-systems-with-ai-nestjs-pinecone-mongodb-and-openai-in-action-7b9139e6bc49">Building Smarter Job Matching Systems with AI: NestJS, Pinecone, MongoDB, and OpenAI in Action</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resolving RPC Exception Handling Issues in NestJS Microservices with Redis]]></title>
            <link>https://blog.stackademic.com/resolving-rpc-exception-handling-issues-in-nestjs-microservices-with-redis-c31ff08e75d5?source=rss-8dd0bd4ca9c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c31ff08e75d5</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[rpc]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Moise rushanika]]></dc:creator>
            <pubDate>Wed, 20 Nov 2024 13:55:55 GMT</pubDate>
            <atom:updated>2024-11-20T16:11:18.021Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*os55wSbdfH04XGrBzIw3BA.png" /></figure><p>When working with <strong>NestJS</strong> microservices using Redis, a common issue developers encounter is the inability to properly catch <strong>RPC exceptions</strong> on the server side. This article will address the issue and provide a step-by-step solution, complete with clear examples.</p><h3>Understanding the Problem</h3><p>In a NestJS microservices architecture, <strong>RPC (Remote Procedure Call)</strong> is a pattern where clients make requests to a server and wait for a response. NestJS supports this pattern through message brokers like Redis.</p><p>However, when an <strong>exception is thrown</strong> on the server during the execution of an RPC handler, the client may fail to receive the expected error response or the error is not properly handled. This happens because of improper configuration or missing handlers for exceptions in the microservice setup.</p><h3>Solution</h3><p>Here’s how to fix and correctly handle RPC exceptions in a NestJS microservice using Redis.</p><p>Step 1: Set Up a Basic NestJS Microservice</p><p>Ensure you have a NestJS microservice communicating via Redis.</p><p><strong>Install Required Dependencies:</strong></p><pre>npm install --save @nestjs/microservices redis</pre><p>Microservice Server (server.module.ts):</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { ClientsModule, Transport } from &#39;@nestjs/microservices&#39;;<br>import { AppController } from &#39;./app.controller&#39;;<br><br>@Module({<br>  imports: [<br>    ClientsModule.register([<br>      {<br>        name: &#39;REDIS_SERVICE&#39;,<br>        transport: Transport.REDIS,<br>        options: {<br>          url: &#39;redis://localhost:6379&#39;,<br>        },<br>      },<br>    ]),<br>  ],<br>  controllers: [AppController],<br>})<br>export class AppModule {}</pre><p>Microservice Controller (app.controller.ts):</p><pre>import { Controller } from &#39;@nestjs/common&#39;;<br>import { MessagePattern, RpcException } from &#39;@nestjs/microservices&#39;;<br><br>@Controller()<br>export class AppController {<br>  @MessagePattern(&#39;sum_numbers&#39;)<br>  async handleSumNumbers(data: { num1: number; num2: number }) {<br>    const { num1, num2 } = data;<br><br>    // Throwing an exception if input is invalid<br>    if (typeof num1 !== &#39;number&#39; || typeof num2 !== &#39;number&#39;) {<br>      throw new RpcException(&#39;Invalid input: numbers are required&#39;);<br>    }<br><br>    return { sum: num1 + num2 };<br>  }<br>}</pre><p>Step 2: Add RPC Exception Handling on the Server</p><p>By default, <strong>RPC exceptions</strong> must be caught using the RpcException class provided by NestJS. However, you also need to ensure that the error is serialized and returned properly.</p><p><strong>Enable Exception Filters:</strong></p><p>Create a global exception filter for the microservice:</p><pre>import { Catch, RpcExceptionFilter, ArgumentsHost } from &#39;@nestjs/common&#39;;<br>import { Observable, throwError } from &#39;rxjs&#39;;<br>import { RpcException } from &#39;@nestjs/microservices&#39;;<br><br>@Catch(RpcException)<br>export class CustomRpcExceptionFilter implements RpcExceptionFilter {<br>  catch(exception: RpcException, host: ArgumentsHost): Observable&lt;any&gt; {<br>    const errorResponse = {<br>      status: &#39;error&#39;,<br>      message: exception.getError(),<br>    };<br><br>    return throwError(() =&gt; errorResponse);<br>  }<br>}</pre><p>Apply the filter in the <strong>main.ts</strong> file of the microservice:</p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>import { MicroserviceOptions, Transport } from &#39;@nestjs/microservices&#39;;<br>import { CustomRpcExceptionFilter } from &#39;./filters/rpc-exception.filter&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.createMicroservice&lt;MicroserviceOptions&gt;(<br>    AppModule,<br>    {<br>      transport: Transport.REDIS,<br>      options: { url: &#39;redis://localhost:6379&#39; },<br>    },<br>  );<br><br>  app.useGlobalFilters(new CustomRpcExceptionFilter());<br><br>  await app.listen();<br>}<br>bootstrap();</pre><p>Step 3: Set Up the Client to Handle Errors</p><p><strong>Client Setup:</strong></p><pre>import { Injectable, OnModuleInit } from &#39;@nestjs/common&#39;;<br>import { ClientProxy, ClientProxyFactory, Transport } from &#39;@nestjs/microservices&#39;;<br><br>@Injectable()<br>export class AppService implements OnModuleInit {<br>  private client: ClientProxy;<br><br>  onModuleInit() {<br>    this.client = ClientProxyFactory.create({<br>      transport: Transport.REDIS,<br>      options: { url: &#39;redis://localhost:6379&#39; },<br>    });<br>  }<br><br>  async callSumNumbers(num1: number, num2: number) {<br>    try {<br>      const response = await this.client<br>        .send(&#39;sum_numbers&#39;, { num1, num2 })<br>        .toPromise();<br><br>      console.log(&#39;Response:&#39;, response);<br>      return response;<br>    } catch (error) {<br>      console.error(&#39;Error from server:&#39;, error);<br>      throw error;<br>    }<br>  }<br>}</pre><p><strong>Client Error Handling:</strong> When calling the server, the client will now correctly receive serialized error responses. For instance:</p><pre>// Example Response from Server in case of invalid input:<br>{<br>  status: &#39;error&#39;,<br>  message: &#39;Invalid input: numbers are required&#39;<br>}</pre><p>Step 4: Test the Implementation</p><ol><li>Start the Redis server:</li></ol><pre>redis-server</pre><p>2. Run the Microservice Server:</p><pre>npm run start:microservice</pre><p><strong>3. </strong>Run the Client and call the callSumNumbers method with valid and invalid inputs to verify proper exception handling.</p><h3>Conclusion</h3><p>By implementing a custom RpcExceptionFilter and properly setting up error serialization, you can ensure that your NestJS microservice with Redis correctly handles RPC exceptions. This not only improves error management but also enhances the reliability of your microservice architecture.</p><p>For further questions or issues, feel free to reach out or consult the <a href="https://docs.nestjs.com/microservices">Nest Documentation</a></p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c31ff08e75d5" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/resolving-rpc-exception-handling-issues-in-nestjs-microservices-with-redis-c31ff08e75d5">Resolving RPC Exception Handling Issues in NestJS Microservices with Redis</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Coding Challenges: A Guide to Common Problem-Solving Techniques]]></title>
            <link>https://blog.stackademic.com/mastering-coding-challenges-a-guide-to-common-problem-solving-techniques-46df0fc06650?source=rss-8dd0bd4ca9c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/46df0fc06650</guid>
            <category><![CDATA[problem-solving]]></category>
            <dc:creator><![CDATA[Moise rushanika]]></dc:creator>
            <pubDate>Sat, 19 Oct 2024 22:55:50 GMT</pubDate>
            <atom:updated>2024-10-21T03:00:07.883Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*19x_CI_0iVObzwBNgCqovw.jpeg" /></figure><p>Coding challenges are essential to technical interviews, competitive programming, and everyday problem-solving in software development. They test your ability to solve problems efficiently and effectively, but the key to cracking these challenges lies in understanding and applying the right techniques. Below is a guide to some of the most widely used techniques that will help you confidently approach and solve coding problems.</p><h3>1. Brute Force</h3><ul><li><strong>What it is</strong>: A straightforward and exhaustive approach that tries all possible solutions.</li><li><strong>When to use</strong>: Ideal for small datasets or when initially brainstorming solutions. Though it may not always be the most efficient, brute force can help you understand the problem thoroughly.</li><li><strong>Example</strong>: In the case of generating all combinations or permutations of a set, a brute force solution explores every possible combination until the correct one is found.</li><li><strong>Drawback</strong>: This method becomes inefficient for large inputs as it can take exponential time to explore all possibilities.</li></ul><pre>function findPairs(nums: number[], target: number): number[][] {<br>    const pairs: number[][] = [];<br>    for (let i = 0; i &lt; nums.length; i++) {<br>        for (let j = i + 1; j &lt; nums.length; j++) {<br>            if (nums[i] + nums[j] === target) {<br>                pairs.push([nums[i], nums[j]]);<br>            }<br>        }<br>    }<br>    return pairs;<br>}<br><br>// Usage<br>console.log(findPairs([1, 2, 3, 4, 5], 5)); // Output: [[1,4], [2,3]]</pre><h3>2. Two-Pointer Technique</h3><ul><li><strong>What it is</strong>: A technique that uses two pointers, typically one starting from the beginning and the other from the end, to traverse a data structure.</li><li><strong>When to use</strong>: Effective for problems that involve sorted arrays or lists, especially when looking for pairs or triplets with specific properties.</li><li><strong>Example</strong>: To find two numbers in a sorted array that sum up to a specific target, two pointers can help by moving one pointer from the start and another from the end to reduce search space.</li></ul><pre>function threeSum(nums: number[]): number[][] {<br>    const results: number[][] = [];<br>    nums.sort((a, b) =&gt; a - b);<br><br>    for (let i = 0; i &lt; nums.length - 2; i++) {<br>        if (i &gt; 0 &amp;&amp; nums[i] === nums[i - 1]) continue; // Skip duplicates<br>        let left = i + 1;<br>        let right = nums.length - 1;<br><br>        while (left &lt; right) {<br>            const sum = nums[i] + nums[left] + nums[right];<br>            if (sum === 0) {<br>                results.push([nums[i], nums[left], nums[right]]);<br>                while (nums[left] === nums[left + 1]) left++;<br>                while (nums[right] === nums[right - 1]) right--;<br>                left++;<br>                right--;<br>            } else if (sum &lt; 0) {<br>                left++;<br>            } else {<br>                right--;<br>            }<br>        }<br>    }<br>    return results;<br>}<br><br>// Usage<br>console.log(threeSum([-1, 0, 1, 2, -1, -4])); // Output: [[-1, -1, 2], [-1, 0, 1]]</pre><h3>3. Sliding Window</h3><ul><li><strong>What it is</strong>: A dynamic technique that involves maintaining a subset of elements (a “window”) and moving that window across the data structure to find the optimal result.</li><li><strong>When to use</strong>: It’s particularly useful for problems where you’re dealing with contiguous subarrays or substrings.</li><li><strong>Example</strong>: Finding the maximum sum of a contiguous subarray of a fixed length in an array is a classic problem solved using the sliding window technique.</li></ul><pre>function maxSubarraySum(nums: number[], k: number): number {<br>    let maxSum = 0;<br>    let currentSum = 0;<br><br>    for (let i = 0; i &lt; k; i++) {<br>        currentSum += nums[i];<br>    }<br><br>    maxSum = currentSum;<br><br>    for (let i = k; i &lt; nums.length; i++) {<br>        currentSum += nums[i] - nums[i - k];<br>        maxSum = Math.max(maxSum, currentSum);<br>    }<br><br>    return maxSum;<br>}<br><br>// Usage<br>console.log(maxSubarraySum([1, 2, 3, 4, 5, 6], 3)); // Output: 15</pre><h3>4. Backtracking</h3><ul><li><strong>What it is</strong>: A recursive technique that explores all potential configurations of a problem. When a solution path is determined to be invalid, it “backtracks” to explore other paths.</li><li><strong>When to use</strong>: Effective for combinatorial problems or constraint satisfaction problems.</li><li><strong>Example</strong>: Solving the N-Queens problem, where you try to place queens on a chessboard such that no two queens threaten each other. The algorithm tries different placements and backtracks when a conflict arises.</li></ul><pre>function solveNQueens(n: number): string[][] {<br>    const solutions: string[][] = [];<br>    const board: string[] = Array(n).fill(&#39;.&#39;.repeat(n));<br>    const cols = new Set&lt;number&gt;();<br>    const diag1 = new Set&lt;number&gt;();<br>    const diag2 = new Set&lt;number&gt;();<br><br>    function backtrack(row: number) {<br>        if (row === n) {<br>            solutions.push([...board]);<br>            return;<br>        }<br><br>        for (let col = 0; col &lt; n; col++) {<br>            if (cols.has(col) || diag1.has(row - col) || diag2.has(row + col)) continue;<br>            <br>            board[row] = &#39;.&#39;.repeat(col) + &#39;Q&#39; + &#39;.&#39;.repeat(n - col - 1);<br>            cols.add(col);<br>            diag1.add(row - col);<br>            diag2.add(row + col);<br><br>            backtrack(row + 1);<br><br>            cols.delete(col);<br>            diag1.delete(row - col);<br>            diag2.delete(row + col);<br>        }<br>    }<br><br>    backtrack(0);<br>    return solutions;<br>}<br><br>// Usage<br>console.log(solveNQueens(4)); // Output: Board configurations for 4-Queens</pre><h3>5. Dynamic Programming (DP)</h3><ul><li><strong>What it is</strong>: This technique solves complex problems by breaking them down into simpler overlapping subproblems and storing the results of these subproblems to avoid redundant calculations.</li><li><strong>When to use</strong>: Ideal for optimization problems where the problem exhibits <strong>optimal substructure</strong> and <strong>overlapping subproblems</strong>.</li><li><strong>Example</strong>: The Fibonacci sequence can be solved using dynamic programming by storing the results of smaller subproblems (i.e., previous Fibonacci numbers) and building up the solution.</li></ul><pre>function fibonacci(n: number): number {<br>    const dp = [0, 1];<br>    for (let i = 2; i &lt;= n; i++) {<br>        dp[i] = dp[i - 1] + dp[i - 2];<br>    }<br>    return dp[n];<br>}<br><br>// Usage<br>console.log(fibonacci(10)); // Output: 55</pre><h3>6. Greedy Algorithms</h3><ul><li><strong>What it is</strong>: This technique builds a solution step-by-step, always choosing the option that provides the most immediate benefit (local optimum).</li><li><strong>When to use</strong>: When a problem can be solved by making locally optimal choices that lead to a globally optimal solution.</li><li><strong>Example</strong>: The coin change problem can be solved using a greedy algorithm by always choosing the largest coin denomination possible.</li></ul><pre>function minCoins(coins: number[], amount: number): number {<br>    coins.sort((a, b) =&gt; b - a); // Sort in descending order<br>    let count = 0;<br>    for (const coin of coins) {<br>        count += Math.floor(amount / coin);<br>        amount %= coin;<br>    }<br>    return amount === 0 ? count : -1;<br>}<br><br>// Usage<br>console.log(minCoins([1, 2, 5], 11)); // Output: 3 (5 + 5 + 1)</pre><h3>7. Divide and Conquer</h3><ul><li><strong>What it is</strong>: A technique that breaks a problem into smaller subproblems, solves each subproblem independently, and then combines the results to get the final solution.</li><li><strong>When to use</strong>: Useful for problems that can naturally be split into smaller instances of the same problem.</li><li><strong>Example</strong>: Sorting algorithms like merge sort and quicksort use divide and conquer by dividing the array into smaller parts, sorting them, and then merging the results.</li></ul><pre>function mergeSort(arr: number[]): number[] {<br>    if (arr.length &lt;= 1) return arr;<br><br>    const mid = Math.floor(arr.length / 2);<br>    const left = mergeSort(arr.slice(0, mid));<br>    const right = mergeSort(arr.slice(mid));<br><br>    return merge(left, right);<br>}<br><br>function merge(left: number[], right: number[]): number[] {<br>    const result: number[] = [];<br>    let i = 0, j = 0;<br><br>    while (i &lt; left.length &amp;&amp; j &lt; right.length) {<br>        if (left[i] &lt; right[j]) {<br>            result.push(left[i++]);<br>        } else {<br>            result.push(right[j++]);<br>        }<br>    }<br><br>    return result.concat(left.slice(i)).concat(right.slice(j));<br>}<br><br>// Usage<br>console.log(mergeSort([3, 1, 4, 1, 5, 9])); // Output: [1, 1, 3, 4, 5, 9]</pre><h3>8. Graph Algorithms</h3><ul><li><strong>What it is</strong>: These algorithms work with graph structures (nodes connected by edges) and solve problems related to networks, paths, or connectivity.</li><li><strong>When to use</strong>: Essential for problems involving maps, networks, or any data represented as nodes and edges.</li><li><strong>Example</strong>: Depth-first search (DFS) and breadth-first search (BFS) are used to traverse graphs, while Dijkstra’s algorithm finds the shortest path between nodes in a weighted graph.</li></ul><pre>function bfs(graph: number[][], start: number): number[] {<br>    const visited = new Set&lt;number&gt;();<br>    const queue: number[] = [start];<br>    const result: number[] = [];<br><br>    while (queue.length) {<br>        const node = queue.shift()!;<br>        if (!visited.has(node)) {<br>            visited.add(node);<br>            result.push(node);<br>            queue.push(...graph[node].filter(n =&gt; !visited.has(n)));<br>        }<br>    }<br><br>    return result;<br>}<br><br>// Usage (Adjacency List)<br>const graph = [<br>    [1, 2],<br>    [0, 3, 4],<br>    [0, 5],<br>    [1],<br>    [1],<br>    [2]<br>];<br>console.log(bfs(graph, 0)); // Output: [0, 1, 2, 3, 4, 5]</pre><h3>9. Hashing</h3><ul><li><strong>What it is</strong>: This technique involves using a hash table or dictionary to store and retrieve data in constant time on average.</li><li><strong>When to use</strong>: Useful for problems involving frequent lookups or counting frequencies.</li><li><strong>Example</strong>: In problems where you need to find two numbers that sum to a target value, using a hash table to store and look up values can reduce the time complexity from O(n2)O(n²)O(n2) to O(n)O(n)O(n).</li></ul><pre>function firstNonRepeatingChar(str: string): string | null {<br>    const charCount: Record&lt;string, number&gt; = {};<br><br>    for (const char of str) {<br>        charCount[char] = (charCount[char] || 0) + 1;<br>    }<br><br>    for (const char of str) {<br>        if (charCount[char] === 1) return char;<br>    }<br><br>    return null;<br>}<br><br>// Usage<br>console.log(firstNonRepeatingChar(&#39;swiss&#39;)); // Output: &#39;w&#39;</pre><h3>10. Bit Manipulation</h3><ul><li><strong>What it is</strong>: A low-level technique that operates on the binary representations of numbers using bitwise operations.</li><li><strong>When to use</strong>: Common in problems where you need to optimize space or deal with combinations or parity checks.</li><li><strong>Example</strong>: Counting the number of set bits (1s) in a binary number or determining if a number is a power of two can be efficiently done using bitwise operations.</li></ul><pre>function singleNumber(nums: number[]): number {<br>    return nums.reduce((acc, num) =&gt; acc ^ num, 0);<br>}<br><br>// Usage<br>console.log(singleNumber([4, 1, 2, 1, 2])); // Output: 4</pre><h3>11. Sorting and Searching</h3><ul><li><strong>What it is</strong>: Sorting arranges elements in a specific order, and searching finds specific elements within that order.</li><li><strong>When to use</strong>: Fundamental for problems that involve organizing or locating data.</li><li><strong>Example 1</strong>: Binary search is a classic algorithm that, given a sorted array, can find a target element in O(log⁡n)O(\log n)O(logn) time.</li></ul><pre>function binarySearch(arr: number[], target: number): number {<br>    let left = 0;<br>    let right = arr.length - 1;<br><br>    while (left &lt;= right) {<br>        const mid = Math.floor((left + right) / 2);<br>        if (arr[mid] === target) return mid;<br>        if (arr[mid] &lt; target) left = mid + 1;<br>        else right = mid - 1;<br>    }<br><br>    return -1; // Target not found<br>}<br><br>// Usage<br>console.log(binarySearch([1, 2, 3, 4, 5, 6, 7], 4)); // Output: 3</pre><ul><li><strong>Example 2: </strong>Quick sort is an efficient, O(n log n) average time complexity, comparison-based sorting algorithm. It works by selecting a &quot;pivot&quot; element and partitioning the array into two subarrays, recursively sorting each one.</li></ul><pre>function quickSort(arr: number[]): number[] {<br>    if (arr.length &lt;= 1) return arr;<br><br>    const pivot = arr[Math.floor(arr.length / 2)];<br>    const left = arr.filter(x =&gt; x &lt; pivot);<br>    const right = arr.filter(x =&gt; x &gt; pivot);<br>    const equal = arr.filter(x =&gt; x === pivot);<br><br>    return [...quickSort(left), ...equal, ...quickSort(right)];<br>}<br><br>// Usage<br>console.log(quickSort([3, 6, 8, 10, 1, 2, 1])); // Output: [1, 1, 2, 3, 6, 8, 10]</pre><h3>12. Randomized Algorithms</h3><ul><li><strong>What it is</strong>: These algorithms use randomness as part of their logic to achieve good average-case performance.</li><li><strong>When to use</strong>: Useful when deterministic algorithms may be too slow or complex, and you’re willing to trade off consistency for speed.</li><li><strong>Example 1</strong>: Randomized quicksort selects a random pivot to avoid worst-case scenarios, leading to O(nlog⁡n)O(n \log n)O(nlogn) expected time complexity.</li></ul><pre>function randomizedQuickSort(arr: number[]): number[] {<br>    if (arr.length &lt;= 1) return arr;<br><br>    const pivotIndex = Math.floor(Math.random() * arr.length);<br>    const pivot = arr[pivotIndex];<br>    const left = arr.filter(x =&gt; x &lt; pivot);<br>    const right = arr.filter(x =&gt; x &gt; pivot);<br>    const equal = arr.filter(x =&gt; x === pivot);<br><br>    return [...randomizedQuickSort(left), ...equal, ...randomizedQuickSort(right)];<br>}<br><br>// Usage<br>console.log(randomizedQuickSort([3, 6, 8, 10, 1, 2, 1])); // Output: [1, 1, 2, 3, 6, 8, 10]</pre><ul><li><strong>Example 2</strong>: Reservoir sampling is used to randomly select k items from a stream or a large dataset when the size of the dataset is unknown or too large to store in memory</li></ul><pre>function reservoirSampling(stream: number[], k: number): number[] {<br>    const reservoir: number[] = stream.slice(0, k);<br><br>    for (let i = k; i &lt; stream.length; i++) {<br>        const j = Math.floor(Math.random() * (i + 1));<br>        if (j &lt; k) {<br>            reservoir[j] = stream[i];<br>        }<br>    }<br><br>    return reservoir;<br>}<br><br>// Usage: Randomly select 3 numbers from a stream<br>console.log(reservoirSampling([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)); <br>// Output: [ Random 3 elements from the stream ]</pre><h3>Conclusion</h3><p>When solving coding challenges, the key is to recognize which technique best fits the problem at hand. Different problems may require different strategies, and having a solid understanding of these techniques can drastically improve your efficiency. In many cases, combining these techniques or thinking of problems in multiple ways can lead to more elegant and optimized solutions.</p><ul><li><strong>Brute Force</strong>: Easy to implement but inefficient.</li><li><strong>Two-Pointer</strong>: Great for sorting data and finding pairs.</li><li><strong>Sliding Window</strong>: Optimizes for subarray or substring problems.</li><li><strong>Backtracking</strong>: Perfect for constraint-based exploration.</li><li><strong>Dynamic Programming</strong>: Ideal for optimization with overlapping subproblems.</li><li><strong>Greedy</strong>: Fast but requires the problem to fit certain criteria.</li><li><strong>Divide and Conquer</strong>: Efficient for problems that can be split.</li><li><strong>Graph Algorithms</strong>: Crucial for pathfinding and connectivity.</li><li><strong>Hashing</strong>: Speeds up lookups and frequency counts.</li><li><strong>Bit Manipulation</strong>: Useful for binary-related problems.</li><li><strong>Sorting and Searching</strong>: Fundamental for ordered data.</li><li><strong>Randomized</strong>: Provides speed at the cost of consistency.</li></ul><p>By mastering these techniques, you’ll be well-equipped to tackle coding challenges efficiently and effectively.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46df0fc06650" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/mastering-coding-challenges-a-guide-to-common-problem-solving-techniques-46df0fc06650">Mastering Coding Challenges: A Guide to Common Problem-Solving Techniques</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalable Strategies for Verifying Username Availability Across Billion User Bases]]></title>
            <link>https://blog.stackademic.com/scalable-strategies-for-verifying-username-availability-across-billion-user-bases-a4f94ff3e647?source=rss-8dd0bd4ca9c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4f94ff3e647</guid>
            <category><![CDATA[bloom-filter]]></category>
            <category><![CDATA[nest]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[redi̇s]]></category>
            <dc:creator><![CDATA[Moise rushanika]]></dc:creator>
            <pubDate>Sun, 06 Oct 2024 16:54:28 GMT</pubDate>
            <atom:updated>2024-10-07T03:23:24.414Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Have you ever tried to register for an app, only to find out that your preferred username is already taken? While this might seem like a minor inconvenience, it’s a significant technical challenge for applications that handle massive user bases. The process of determining whether a username is available can be approached in several ways, each with its strengths and weaknesses. In this article. In this guide, we will explore three common methods for solving this problem in a <strong>NestJS</strong> application connected to any databases:</p><ol><li>Traditional Database Query</li><li>Redis Cache Strategy</li><li>Bloom Filter Approach</li></ol><h3>Method 1: Database Query Approach</h3><p>The simplest and most direct way to check if a username exists is by querying the PostgreSQL database. However, as the number of users grows, database queries become slower, leading to performance issues such as high latency and scalability problems.</p><pre>// user.service.ts<br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { InjectRepository } from &#39;@nestjs/typeorm&#39;;<br>import { Repository } from &#39;typeorm&#39;;<br>import { User } from &#39;./user.entity&#39;;<br><br>@Injectable()<br>export class UserService {<br>  constructor(<br>    @InjectRepository(User)<br>    private readonly userRepository: Repository&lt;User&gt;,<br>  ) {}<br><br>  // Method to check if username exists<br>  async checkUsernameExists(username: string): Promise&lt;boolean&gt; {<br>    const user = await this.userRepository.findOne({<br>      where: { username },<br>    });<br>    return !!user;<br>  }<br>}</pre><p>While this method works fine for smaller datasets, it can become inefficient when dealing with millions of users because:</p><ol><li><strong>High Latency:</strong></li></ol><ul><li>When querying a large database, performance can suffer due to increased latency. Each query involves network communication between the application and the database server, adding to the delay.</li></ul><p><strong>2. Heavy Database Load:</strong></p><ul><li>Regular SELECT queries to check username uniqueness consume significant database resources, including CPU and I/O. This can lead to bottlenecks, especially during peak times.</li></ul><p><strong>3. Scalability Issues:</strong></p><ul><li>Databases have inherent limitations in handling a large number of concurrent connections. As user registrations increase, the database may struggle to keep up, leading to performance degradation. Scaling the database vertically (adding more resources) can be expensive and has its limits.</li></ul><h3>Method 2: Redis Cache Solution</h3><p>A more optimized approach involves using <strong>Redis</strong> as a caching layer to reduce the number of direct database queries. Redis allows us to store usernames in a Redis hash map, resulting in faster checks.</p><h4>How It Works:</h4><ul><li><strong>Storing Usernames in Redis</strong>: Store usernames in a Redis cache upon user registration or login. Before querying the database, check if the username exists in Redis.</li><li><strong>Faster Checks</strong>: Redis operates in memory, so checking for the existence of a key is significantly faster than a database query.</li></ul><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { InjectRepository } from &#39;@nestjs/typeorm&#39;;<br>import { Repository } from &#39;typeorm&#39;;<br>import { RedisService } from &#39;nestjs-redis&#39;;<br>import { User } from &#39;./user.entity&#39;;<br><br>@Injectable()<br>export class UserService {<br>  private redisClient;<br><br>  constructor(<br>    @InjectRepository(User)<br>    private readonly userRepository: Repository&lt;User&gt;,<br>    private readonly redisService: RedisService,<br>  ) {<br>    this.redisClient = this.redisService.getClient();<br>  }<br><br>  async checkUsernameExists(username: string): Promise&lt;boolean&gt; {<br>    // Check Redis cache first<br>    const cacheKey = `username:${username}`;<br>    const cachedUser = await this.redisClient.get(cacheKey);<br><br>    if (cachedUser) {<br>      return true;<br>    }<br><br>    // If not found in Redis, check the database<br>    const user = await this.userRepository.findOne({ where: { username } });<br><br>    if (user) {<br>      // Add the username to Redis for future lookups<br>      await this.redisClient.set(cacheKey, &#39;true&#39;);<br>      return true;<br>    }<br><br>    return false;<br>  }<br>}</pre><p>In this approach, Redis is checked first to avoid unnecessary database queries. If the username is not in Redis, a database query is performed, and if found, the username is cached in Redis for future lookups. This method is significantly faster than querying the database every time but may be constrained by memory usage.</p><h4>Challenges:</h4><ul><li><strong>Memory Usage</strong>: Storing billions of usernames in Redis can consume large amounts of memory. Each username may take approximately 15 bytes, so 1 billion usernames would require around 15 GB of memory.</li><li><strong>Consistency</strong>: The cache needs to be kept consistent with the database, which can be tricky if updates are not properly synchronized.</li></ul><h3>Method 3: Bloom Filter Technique</h3><p>When memory efficiency is critical, a <strong>Bloom Filter</strong> offers an elegant solution. A Bloom Filter is a probabilistic data structure that allows you to test whether an element is part of a set, using less memory than storing the actual data. The trade-off is the potential for <strong>false positives</strong> (i.e., the filter might say a username exists when it does not), but <strong>no false negatives</strong> (if it says a username doesn’t exist, it definitely doesn’t).</p><h4>How It Works:</h4><ol><li><strong>Bit Array and Hash Functions</strong>: A Bloom Filter uses a bit array and multiple hash functions to map usernames to bits in the array.</li><li><strong>Adding a Username</strong>: When a username is added, several bits in the array are flipped to 1.</li><li><strong>Checking for a Username</strong>: To check if a username exists, the same hash functions are used. If all corresponding bits are 1, the username <strong>might</strong> exist (false positive). If any bit is 0, it definitely does not exist.</li></ol><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { InjectRepository } from &#39;@nestjs/typeorm&#39;;<br>import { Repository } from &#39;typeorm&#39;;<br>import { User } from &#39;./user.entity&#39;;<br>import { BloomFilter } from &#39;bloom-filters&#39;;<br><br>@Injectable()<br>export class UserService {<br>  private bloomFilter: BloomFilter;<br><br>  constructor(<br>    @InjectRepository(User)<br>    private readonly userRepository: Repository&lt;User&gt;,<br>  ) {<br>    // Initialize the Bloom Filter with a size of 20 million and 5 hash functions<br>    this.bloomFilter = new BloomFilter(20 * 1000 * 1000, 5);<br>  }<br><br>  // Add a username to the Bloom Filter<br>  async addUsernameToFilter(username: string): Promise&lt;void&gt; {<br>    this.bloomFilter.add(username);<br>  }<br><br>  // Check if a username exists using the Bloom Filter<br>  async checkUsernameExists(username: string): Promise&lt;boolean&gt; {<br>    return this.bloomFilter.has(username);<br>  }<br>}</pre><p><strong>Output:</strong></p><pre>Username &#39;moise&#39; exists? true<br>Username &#39;moise&#39; exists? false</pre><p><strong>Visual Explanation of Bloom Filters</strong></p><p>The diagram below visually explains how a Bloom Filter works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OlWUUeFqcA9G1wJ2Ww9rmg.jpeg" /></figure><p><strong>Part (a): Inserting a Sequence</strong></p><ul><li><strong>Sequence “ACCGTAG”</strong>: Imagine we want to check if this sequence is in our set.</li><li><strong>k-mers</strong>: The sequence is broken down into smaller parts called “k-mers” (like chunks or fragments). For example, “ACCG”, “CCGT”, “CGTA”, and “GTAG”.</li><li><strong>Hashing k-mers</strong>: Each of these k-mers is passed through a set of hash functions. These hash functions take the k-mers and map them to specific positions in a bit array.</li><li><strong>Setting Bits</strong>: For each k-mer, the corresponding bits in the bit array are set to 1. The bit array is initially all zeros, but as we add k-mers, specific bits are turned on (set to 1).</li></ul><p><strong>Part (b): Querying a Sequence</strong></p><ul><li><strong>Query “CGTAT”</strong>: Now, let’s say we want to check if “CGTAT” is in our set.</li><li><strong>k-mers</strong>: Like before, this sequence is broken down into k-mers, such as “CGTA” and “GTAT”.</li><li><strong>Checking Bits</strong>: These k-mers are hashed, and we check the corresponding bits in the bit array:</li><li>If all bits are set to 1 (like with “CGTA”), it suggests that the sequence <em>might</em> be in the set.</li><li>If even one bit is 0 (like with “GTAT”), it means the sequence is definitely not in the set.</li></ul><p><strong>Summary:</strong></p><ul><li><strong>Bloom Filter Benefits</strong>: This method is memory efficient and quick for checking if something is likely in a set.</li><li><strong>False Positives</strong>: Sometimes, it may incorrectly indicate that an item is in the set when it’s not (this is a “false positive”).</li><li><strong>Definite Negatives</strong>: If the check indicates an item is not in the set, it’s guaranteed to be correct.</li></ul><p>This diagram visually shows how Bloom Filters can be used to efficiently check for the presence or absence of data in a set, making them useful in many scenarios like filtering or speeding up database queries.</p><h4>Benefits:</h4><ul><li><strong>Memory Efficient</strong>: Uses significantly less memory compared to caching all usernames.</li><li><strong>Fast Lookups</strong>: Lookup time is constant and independent of the number of users.</li></ul><h3>Conclusion</h3><ul><li><strong>Database Query</strong>: Simple but not scalable for large datasets.</li><li><strong>Redis Cache</strong>: Improves performance by reducing the number of database queries, but has memory constraints.</li><li><strong>Bloom Filter</strong>: Offers a highly memory-efficient solution for large datasets with fast lookups, though it introduces a trade-off with false positives.</li></ul><p>Each method has its strengths and weaknesses, and the right solution depends on your specific requirements, including the size of the user base, the available resources, and the acceptable trade-offs between performance, memory, and accuracy.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4f94ff3e647" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/scalable-strategies-for-verifying-username-availability-across-billion-user-bases-a4f94ff3e647">Scalable Strategies for Verifying Username Availability Across Billion User Bases</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Essential Virtues of Exceptional Developers]]></title>
            <link>https://blog.stackademic.com/the-essential-virtues-of-exceptional-developers-7914eac84662?source=rss-8dd0bd4ca9c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7914eac84662</guid>
            <dc:creator><![CDATA[Moise rushanika]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 22:56:55 GMT</pubDate>
            <atom:updated>2024-09-03T03:43:08.494Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*brUCaq0zziVP2ES1KoZINg.png" /></figure><h3>The Three Virtues of a Great Developer: Patience, Humility, and Passion</h3><p>In the fast-paced world of software development, where technology evolves at a breakneck speed, it’s easy to get caught up in the race to learn the latest languages, frameworks, and tools. While technical prowess is undoubtedly important, there are deeper, more enduring qualities that truly define a great developer. These qualities transcend code and algorithms, shaping how developers approach their work, collaborate with others, and navigate the complexities of the software development lifecycle. Among these qualities, three virtues stand out as essential: patience, humility, and passion. Together, these virtues form the foundation of professional excellence, enabling developers to create meaningful, lasting contributions to their teams, their projects, and the broader tech community.</p><h4>1. Patience: The Art of Perseverance</h4><p><strong>“Patience is not the ability to wait, but the ability to keep a good attitude while waiting.”</strong> — Joyce Meyer</p><p>In the context of software development, patience is more than just waiting for code to compile or for a test suite to run. It’s about the perseverance to push through challenges, the resilience to handle setbacks, and the commitment to seeing a project through to completion, no matter how complex or frustrating it may become. Patience is the virtue that allows developers to maintain their focus and composure in the face of obstacles, ensuring that they deliver high-quality, reliable software.</p><p>Consider the process of debugging, a task that every developer is intimately familiar with. Debugging often requires wading through hundreds or even thousands of lines of code to identify the root cause of an issue. The process can be tedious and time-consuming, especially when the bug is elusive or when it involves a complex interaction between different parts of the system. A patient developer approaches debugging with a methodical mindset, systematically testing hypotheses, carefully analyzing the behavior of the code, and patiently working through potential solutions until the issue is resolved.</p><p>Take, for example, a scenario where a developer is working on a mission-critical application that suddenly starts crashing under certain conditions. The crashes are intermittent, making them difficult to reproduce and diagnose. An impatient developer might rush to apply a quick fix, potentially introducing new bugs or overlooking the underlying cause of the problem. In contrast, a patient developer will take the time to gather as much information as possible, such as logs, stack traces, and user reports, and will methodically test different scenarios to isolate the issue. They understand that a hasty solution might only provide temporary relief and that addressing the root cause is essential for long-term stability.</p><p>Patience also plays a crucial role in the design and architecture phases of software development. Building a scalable, maintainable system requires careful consideration of trade-offs, thoughtful planning, and a willingness to iterate on ideas. A patient developer is willing to spend the time necessary to design a system that meets both current and future needs, even if it means delaying the implementation phase. They understand that investing time upfront in design can save countless hours of refactoring and debugging later on.</p><p>Moreover, patience is essential when dealing with legacy codebases. Many developers have found themselves in situations where they need to maintain or extend a codebase that is poorly documented, convoluted, or written in an outdated language. It can be tempting to scrap the old code and start from scratch, but a patient developer recognizes the value of understanding the existing system, learning from its history, and making incremental improvements. This approach not only preserves the knowledge embedded in the legacy code but also reduces the risk of introducing new issues.</p><h4>2. Humility: Embracing the Learning Journey</h4><p><strong>“True humility is not thinking less of yourself; it is thinking of yourself less.”</strong> — C.S. Lewis</p><p>In the ever-evolving field of software development, no one can claim to know everything. New languages, frameworks, and tools are constantly emerging, and what was considered best practice a few years ago may now be outdated. This rapid pace of change requires developers to be lifelong learners, and humility is the virtue that enables them to embrace this continuous learning journey.</p><p>Humility in software development is about recognizing that there is always more to learn, no matter how experienced or knowledgeable one may be. It involves being open to new ideas, willing to admit mistakes, and eager to seek feedback from others. A humble developer understands that their knowledge is limited and that the collective wisdom of the team is far greater than any individual contribution.</p><p>One of the most visible manifestations of humility in a developer is the willingness to ask questions. In a field where expertise is often prized, some developers might feel hesitant to ask questions for fear of appearing ignorant. However, a humble developer understands that asking questions is not a sign of weakness but a powerful tool for learning. Whether they are asking a colleague for clarification on a complex algorithm, seeking advice on a design pattern, or querying a search engine for documentation, they are driven by a desire to deepen their understanding and improve their skills.</p><p>Consider a developer who is working on integrating a new third-party library into an existing project. The library’s documentation is sparse, and the integration process is proving to be more challenging than anticipated. Instead of struggling in silence or attempting to force the integration without fully understanding the implications, a humble developer will reach out to the library’s maintainers, ask questions on relevant forums, or collaborate with colleagues who may have more experience with similar tools. This willingness to seek help not only speeds up the development process but also fosters a culture of collaboration and shared learning.</p><p>Humility also extends to the way developers approach code reviews. A humble developer views code reviews as an opportunity to learn from their peers and to improve their code. They are open to constructive criticism and do not take feedback personally. Instead, they see it as a chance to refine their craft and contribute to the overall quality of the project. Moreover, when reviewing others’ code, a humble developer provides feedback in a respectful and supportive manner, recognizing that the goal is to help their colleagues grow, not to prove their own superiority.</p><p>Another important aspect of humility is the ability to recognize and learn from mistakes. In software development, mistakes are inevitable. Bugs are introduced, assumptions are proven wrong, and deployments go awry. A humble developer does not shy away from these mistakes but instead takes ownership of them, analyzes what went wrong, and learns from the experience. They understand that failure is a valuable teacher and that each mistake is an opportunity for growth.</p><p>For example, imagine a developer who accidentally introduces a bug that causes a critical production system to go down. Instead of deflecting blame or downplaying the severity of the issue, a humble developer will take responsibility, work diligently to resolve the problem, and then conduct a post-mortem to understand the root cause and prevent similar issues in the future. They will also be transparent with their team about what happened, using the experience as a learning opportunity for everyone involved.</p><p>Finally, humility is essential for fostering a collaborative and inclusive team environment. A humble developer recognizes that great ideas can come from anywhere, regardless of seniority, title, or background. They actively seek out diverse perspectives, listen to others with an open mind, and create space for everyone to contribute. This inclusive approach not only leads to better software but also builds a stronger, more cohesive team.</p><h4>3. Passion: The Drive to Innovate</h4><p><strong>“Passion is the genesis of genius.”</strong> — Tony Robbins</p><p>Passion is the third virtue that sets great developers apart from the rest. While technical skills can be learned and honed over time, passion is what drives developers to go above and beyond, explore new possibilities, and push the boundaries of what can be achieved through code. Passionate developers are those who are not just writing code to meet deadlines or to fulfil job requirements; they are doing it because they love it because they are deeply curious about how things work, and because they are driven by a desire to create, innovate, and solve problems.</p><p>A passionate developer is someone who is constantly experimenting with new technologies, learning new languages, and exploring new domains. They are the ones who spend their free time contributing to open-source projects, building side projects, or reading up on the latest trends in the tech industry. Their passion is evident in the way they talk about their work, in the enthusiasm they bring to their projects, and in their relentless pursuit of excellence.</p><p>Consider a developer who, after reading about the potential of machine learning, decides to explore the field by taking online courses, participating in hackathons, and building their own machine learning models. Even though machine learning may not be directly related to their day job, their passion for learning and experimentation drives them to invest time and effort into mastering the subject. Over time, this passion not only enhances their own skills but also benefits their team and organization as they bring new ideas and capabilities to the table.</p><p>Passion also manifests in the way developers approach problem-solving. A passionate developer is not content with just finding a solution; they want to find the best solution. They are willing to put in the extra effort to optimize their code, refactor a clunky piece of logic, or explore alternative approaches that could lead to a more elegant or efficient solution. This drive to continuously improve and strive for excellence is what sets passionate developers apart.</p><p>For example, imagine a developer working on a performance-critical application that is experiencing latency issues. Instead of settling for a quick fix that merely masks the problem, a passionate developer will take the time to profile the application, analyze the performance bottlenecks, and explore various optimization techniques. They might experiment with different data structures, algorithms, or caching strategies, all in the pursuit of achieving the best possible performance. This level of dedication and attention to detail is a hallmark of a developer who is truly passionate about their craft.</p><p>Moreover, passion is what drives developers to stay ahead of the curve in a rapidly changing industry. Technology is constantly evolving, and what was cutting-edge a few years ago may now be obsolete. Passionate developers are those who are always curious about what’s next, and who are eager to explore new</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7914eac84662" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/the-essential-virtues-of-exceptional-developers-7914eac84662">The Essential Virtues of Exceptional Developers</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Microservices in NestJS: Powerful Design Patterns for Flexibility, Resilience, and…]]></title>
            <link>https://blog.stackademic.com/mastering-microservices-in-nestjs-powerful-design-patterns-for-flexibility-resilience-and-64309ae219e8?source=rss-8dd0bd4ca9c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/64309ae219e8</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Moise rushanika]]></dc:creator>
            <pubDate>Sun, 18 Aug 2024 11:53:06 GMT</pubDate>
            <atom:updated>2024-08-19T00:14:46.756Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Microservices in NestJS: Powerful Design Patterns for Flexibility, Resilience, and Scalability</h3><p>Microservices architecture has become the backbone of modern, scalable, and resilient applications. In this article, we’ll explore powerful design patterns that make microservices shine, specifically in the context of NestJS, a progressive Node.js framework.</p><h4>1. 🛡️ Gateway Pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*VSwMw_N97yAM0cJveJmr8Q.png" /></figure><p>The Gateway Pattern acts as the single entry point for all microservice calls. It routes requests to the appropriate service, handles authentication, and logging, and can even aggregate responses.</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { ClientsModule, Transport } from &#39;@nestjs/microservices&#39;;<br>import { GatewayController } from &#39;./gateway.controller&#39;;<br><br>@Module({<br>  imports: [<br>    ClientsModule.register([<br>      { name: &#39;USER_SERVICE&#39;, transport: Transport.TCP },<br>      { name: &#39;ORDER_SERVICE&#39;, transport: Transport.TCP },<br>    ]),<br>  ],<br>  controllers: [GatewayController],<br>})<br>export class GatewayModule {}</pre><pre>import { Controller, Get } from &#39;@nestjs/common&#39;;<br>import { ClientProxy, ClientProxyFactory, Transport } from &#39;@nestjs/microservices&#39;;<br><br>@Controller(&#39;gateway&#39;)<br>export class GatewayController {<br>  private userServiceClient: ClientProxy;<br>  private orderServiceClient: ClientProxy;<br><br>  constructor() {<br>    this.userServiceClient = ClientProxyFactory.create({ transport: Transport.TCP, options: { port: 3001 } });<br>    this.orderServiceClient = ClientProxyFactory.create({ transport: Transport.TCP, options: { port: 3002 } });<br>  }<br><br>  @Get(&#39;user&#39;)<br>  getUser() {<br>    return this.userServiceClient.send({ cmd: &#39;get-user&#39; }, {});<br>  }<br><br>  @Get(&#39;order&#39;)<br>  getOrder() {<br>    return this.orderServiceClient.send({ cmd: &#39;get-order&#39; }, {});<br>  }<br>}</pre><h4>2. 📡 Service Registry Pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*osChHx3VmE_eBvLQ1LeSjg.png" /></figure><p>The Service Registry Pattern allows microservices to discover each other without hardcoding their locations. It’s essential in dynamic environments where services may change IPs or ports.</p><pre>import { Injectable, OnModuleInit } from &#39;@nestjs/common&#39;;<br>import { Consul } from &#39;consul&#39;;<br><br>@Injectable()<br>export class ServiceRegistry implements OnModuleInit {<br>  private consul: Consul;<br><br>  constructor() {<br>    this.consul = new Consul();<br>  }<br><br>  onModuleInit() {<br>    this.consul.agent.service.register({<br>      name: &#39;user-service&#39;,<br>      address: &#39;127.0.0.1&#39;,<br>      port: 3001,<br>    });<br>  }<br>}</pre><h4>3. ⚡ Circuit Breaker Pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*A36A3C4QJ_-dfdUlVUp2Hg.png" /></figure><p>The Circuit Breaker Pattern prevents cascading failures in microservices by breaking the circuit and returning a fallback response when a service fails or is slow to respond.</p><pre>import { Injectable, HttpService } from &#39;@nestjs/common&#39;;<br>import { catchError } from &#39;rxjs/operators&#39;;<br>import { of } from &#39;rxjs&#39;;<br><br>@Injectable()<br>export class CircuitBreakerService {<br>  constructor(private httpService: HttpService) {}<br><br>  getUserData() {<br>    return this.httpService.get(&#39;http://user-service/user&#39;)<br>      .pipe(<br>        catchError(err =&gt; {<br>          console.log(&#39;Service unavailable, returning fallback data&#39;);<br>          return of({ id: &#39;fallback&#39;, name: &#39;Fallback User&#39; });<br>        })<br>      );<br>  }<br>}</pre><h4>4. 🔄 SAGA Pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*7Oj835aBOd4RXfv-kB67dg.png" /></figure><p>The SAGA Pattern manages complex transactions across multiple services by breaking them into smaller steps. Each step in the SAGA can either be completed successfully or trigger compensating transactions to undo the previous steps if something goes wrong.</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { EventPattern } from &#39;@nestjs/microservices&#39;;<br><br>@Injectable()<br>export class SagaService {<br>  @EventPattern(&#39;order-created&#39;)<br>  async handleOrderCreated(data: Record&lt;string, unknown&gt;) {<br>    // Reserve inventory<br>    // If inventory reservation fails, trigger a compensating transaction<br>  }<br><br>  @EventPattern(&#39;payment-processed&#39;)<br>  async handlePaymentProcessed(data: Record&lt;string, unknown&gt;) {<br>    // Confirm order<br>    // If payment fails, trigger a compensating transaction to release inventory<br>  }<br>}</pre><h4>5. 🔧 CQRS (Command Query Responsibility Segregation)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hIVZRiJ1h9hr28rMMeUsFw.png" /></figure><p>CQRS separates read and write operations, improving performance by optimizing each operation type independently. It’s particularly useful in systems with complex querying requirements.</p><pre>import { QueryHandler, IQueryHandler } from &#39;@nestjs/cqrs&#39;;<br><br>export class GetUserQuery {<br>  constructor(public readonly userId: string) {}<br>}<br><br>@QueryHandler(GetUserQuery)<br>export class GetUserHandler implements IQueryHandler&lt;GetUserQuery&gt; {<br>  async execute(query: GetUserQuery) {<br>    // Handle the query, e.g., return user data<br>    return { id: query.userId, name: &#39;John Doe&#39; };<br>  }<br>}</pre><h4>6. 🧱 Bulkhead Pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*EuKaKkI_x_NI_sLsYHD00Q.png" /></figure><p>The Bulkhead Pattern isolates components within a service to prevent failures from spreading, ensuring that one failing service doesn’t bring down others.</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { Queue } from &#39;bull&#39;;<br><br>@Injectable()<br>export class BulkheadService {<br>  private readonly taskQueue: Queue;<br><br>  constructor() {<br>    this.taskQueue = new Queue(&#39;tasks&#39;);<br>  }<br><br>  async handleTask(taskData: any) {<br>    await this.taskQueue.add(taskData);<br>    // Process task without affecting other components<br>  }<br>}</pre><h4>7. 🚗 Sidecar Pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*k9_vozuk04p4Y5WF7k-Xlw.png" /></figure><p>The Sidecar Pattern adds extra functionalities (like monitoring, logging, or proxying) to a service without altering the core service logic.</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { createProxyMiddleware } from &#39;http-proxy-middleware&#39;;<br><br>@Injectable()<br>export class SidecarService {<br>  configure(app: any) {<br>    app.use(&#39;/user&#39;, createProxyMiddleware({ target: &#39;http://localhost:3001&#39;, changeOrigin: true }));<br>  }<br>}</pre><h4>8. 🔗 API Composition Pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*3Cm0-CDjUylrBd-o-OngTg.png" /></figure><p>API Composition orchestrates multiple microservices into a single API response, which is useful when building APIs that aggregate data from different sources.</p><pre>import { Controller, Get } from &#39;@nestjs/common&#39;;<br>import { HttpService } from &#39;@nestjs/common&#39;;<br><br>@Controller(&#39;orders&#39;)<br>export class OrdersController {<br>  constructor(private httpService: HttpService) {}<br><br>  @Get()<br>  async getOrders() {<br>    const user = await this.httpService.get(&#39;http://user-service/user&#39;).toPromise();<br>    const order = await this.httpService.get(&#39;http://order-service/order&#39;).toPromise();<br>    return { ...user.data, ...order.data };<br>  }<br>}</pre><h4>9. ⚙️ Event-Driven Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*DHzt6CeWVc6iZoylhxcl4Q.png" /></figure><p>In Event-Driven Architecture, services react to events asynchronously, making the system more responsive and decoupled.</p><pre>import { Controller } from &#39;@nestjs/common&#39;;<br>import { EventPattern } from &#39;@nestjs/microservices&#39;;<br><br>@Controller()<br>export class EventController {<br>  @EventPattern(&#39;user_created&#39;)<br>  handleUserCreated(data: Record&lt;string, unknown&gt;) {<br>    console.log(&#39;User created event received:&#39;, data);<br>    // React to the event<br>  }<br>}</pre><h4>10. 📊 Database per Service</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*pSqflCoPC1q8L0QlAIyrLg.png" /></figure><p>Each microservice owns its data, stored in its database, ensuring data isolation and independence. This pattern allows microservices to evolve independently.</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { InjectRepository } from &#39;@nestjs/typeorm&#39;;<br>import { Repository } from &#39;typeorm&#39;;<br>import { User } from &#39;./user.entity&#39;;<br><br>@Injectable()<br>export class UserService {<br>  constructor(@InjectRepository(User) private userRepository: Repository&lt;User&gt;) {}<br><br>  findAll() {<br>    return this.userRepository.find();<br>  }<br>}</pre><h4>11. 🔁 Retry Pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*hX4v_D3U94rhxJfr4_HdWQ.png" /></figure><p>The Retry Pattern handles transient failures by retrying failed operations, often with an exponential backoff strategy.</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { HttpService } from &#39;@nestjs/common&#39;;<br>import { catchError, retryWhen, delay, take } from &#39;rxjs/operators&#39;;<br>import { of } from &#39;rxjs&#39;;<br><br>@Injectable()<br>export class RetryService {<br>  constructor(private httpService: HttpService) {}<br><br>  fetchData() {<br>    return this.httpService.get(&#39;http://unreliable-service/data&#39;)<br>      .pipe(<br>        retryWhen(errors =&gt; errors.pipe(delay(1000), take(3))),<br>        catchError(err =&gt; {<br>          console.log(&#39;Failed after retries&#39;);<br>          return of({ fallback: true });<br>        })<br>      );<br>  }<br>}</pre><h4>12. 📂 Configuration Externalization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*kBS0ZqJ_zxW1qrn-YY95vw.png" /></figure><p>Configuration Externalization centralizes configuration management, making it easier to change configuration without redeploying services.</p><pre>import { ConfigModule } from &#39;@nestjs/config&#39;;<br><br>@Module({<br>  imports: [<br>    ConfigModule.forRoot({<br>      isGlobal: true,<br>      envFilePath: &#39;.env&#39;,<br>    }),<br>  ],<br>})<br>export class AppModule {}</pre><h3>Conclusion</h3><p>Microservices architecture, combined with design patterns like those mentioned above, empowers applications to be flexible, resilient, and scalable. NestJS, with its modular approach and powerful abstractions, is an excellent framework for implementing these patterns, ensuring that your application can handle the complexities of modern distributed systems.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64309ae219e8" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/mastering-microservices-in-nestjs-powerful-design-patterns-for-flexibility-resilience-and-64309ae219e8">Mastering Microservices in NestJS: Powerful Design Patterns for Flexibility, Resilience, and…</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Backend Development: A Guide to Design Patterns with Practical Examples]]></title>
            <link>https://blog.stackademic.com/modern-backend-development-a-guide-to-design-patterns-with-practical-examples-77221614c2bb?source=rss-8dd0bd4ca9c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/77221614c2bb</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nestjs-tutorial]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Moise rushanika]]></dc:creator>
            <pubDate>Mon, 29 Jan 2024 15:30:44 GMT</pubDate>
            <atom:updated>2024-02-01T02:44:11.717Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Ft4LrR18KwUr1nVMwKjuA.png" /></figure><p>In software development, design patterns are reusable solutions to common problems that developers encounter. These patterns provide a structure for organizing code that makes it more maintainable, modular, and scalable.</p><p>In modern backend development, design patterns are crucial for building robust and flexible systems that can adapt to changing requirements and user needs.</p><p>In this tutorial, we will explore the most common design patterns used in modern backend development. We’ll also see how to apply them in real-world scenarios.</p><p>Design patterns are proven solutions to commonly occurring problems in software development. They are not specific to any particular programming language or platform but can be applied to any software system.</p><p>In this tutorial, I will be using TypeScript to illustrate the common patterns covered here.</p><h3>What we’ll cover:</h3><ol><li>Importance of Design Patterns in Software Development</li><li>A Brief Overview of Modern Backend Development</li><li>Advantages of Using Design Patterns in Backend Development</li><li>Common Design Patterns for Modern Backend Development<br>– MVC (Model-View-Controller) Pattern<br>– Repository Pattern<br>– Dependency Injection Pattern<br>– Observer Pattern<br>– Decorator Pattern</li><li>Real-world Examples of Design Patterns in Backend Development<br>– MVC Pattern in a Web App<br>– Repository Pattern with a Database<br>– Dependency Injection Pattern for Decoupling Dependencies<br>– Observer Pattern for Event-Driven Programming<br>– Decorator Pattern for Adding Functionality to a Class Dynamically</li><li>Conclusion</li><li>Next Steps</li></ol><h3>Importance of Design Patterns in Software Development</h3><p>Design patterns offer numerous advantages in software development. They can simplify the coding process, enhance code maintainability, and promote code reuse.</p><p>They also help developers write code that is more efficient, scalable, and adaptable. And they’re incredibly beneficial when working on a project with multiple contributors. This is because design patterns provide a shared framework of best practices that can ensure consistency across the codebase.</p><h3>A Brief Overview of Modern Backend Development</h3><p>Modern backend development is all about creating software systems that power the server side of web applications and services.</p><p>To achieve this, backend developers need to design systems that are scalable, reliable, and efficient. This often involves using cloud-based technologies and microservices architecture, which enables developers to build systems that can handle high traffic loads, while also being flexible and easily manageable.</p><p>In addition to the use of modern technologies, design patterns play a crucial role in building robust and maintainable systems. By using established design patterns, developers can create modular, maintainable, and extendable systems that are easier to manage and improve over time.</p><p>Overall, modern backend development requires a deep understanding of software architecture, cloud-based technologies, and design patterns. By leveraging these tools and techniques, backend developers can create systems that are scalable, reliable, efficient, and easy to maintain over time.</p><h3>Advantages of Using Design Patterns in Backend Development</h3><p>Design patterns are tried and tested solutions to common problems that developers encounter in software development. They provide a structured approach to solving these problems, making it easier for developers to write maintainable, scalable, and reusable code.</p><p>In this section, we will discuss the advantages of using design patterns in backend development.</p><ol><li><strong>Code reusability:</strong> One of the main advantages of using design patterns is code reusability. By following a standard structure, developers can easily reuse code in different parts of an application or even in different applications altogether.</li><li><strong>Scalability:</strong> Design patterns allow for scalability in applications, as they provide a structured approach to writing code. This makes it easier to add new features or make changes to existing ones without disrupting the overall architecture of the application.</li><li><strong>Maintainability:</strong> Using design patterns can make code more maintainable, as they provide a standardized approach to solving problems. This makes it easier for developers to understand code written by others and to maintain it over time.</li><li><strong>Reduced errors:</strong> Design patterns are tried and tested solutions to common problems. By using these patterns, developers can avoid common errors and pitfalls that might arise when writing code from scratch.</li><li><strong>Performance:</strong> Design patterns can improve the performance of an application by providing a structured approach to solving problems. This can result in more efficient code that executes faster and uses fewer resources.</li></ol><h3>Common Design Patterns for Modern Backend Development</h3><p>In modern backend development, there are several design patterns that are widely used to build scalable, maintainable, and efficient systems.</p><p>In this section, we will discuss some of the most commonly used design patterns in modern backend development.</p><h3>MVC (Model-View-Controller) Pattern</h3><p>The Model-View-Controller (MVC) pattern is a widely used design pattern in modern backend development. It provides a way to separate the presentation layer (the View) from the business logic and data storage layers (the Model and Controller). This separation allows developers to write more modular and maintainable code.</p><p>In the MVC pattern, the Model represents the data and business logic of the application. The Controller acts as an intermediary between the Model and the View, handling user input and updating the Model accordingly. The View is responsible for presenting data to the user and receiving user input.</p><p>One of the main advantages of using the MVC pattern is that it allows for easy testing and maintenance of the codebase. Since the Model and Controller are separate from the View, it is possible to test and modify each component independently.</p><p>Another benefit of using the MVC pattern is that it lets you reuse code. The Model and Controller can be reused in different Views, providing a more modular approach to software development.</p><p>Overall, the MVC pattern is a useful tool for creating scalable, maintainable, and efficient backend systems. It separates concerns and enables a more modular approach to software development, making it easier to test, maintain, and modify the codebase.</p><h3>Repository Pattern</h3><p>The Repository Pattern is a design pattern that provides an abstraction layer between the data access layer and the rest of the application. It separates the logic that retrieves data from the data storage layer, providing a more modular approach to software development.</p><p>In the Repository Pattern, a repository acts as a mediator between the data storage layer and the application logic layer. It provides a single point of entry for retrieving and manipulating data, allowing the rest of the application to be decoupled from the specifics of the data storage layer. This makes it easier to change the data storage layer without affecting the rest of the application.</p><p>One of the main advantages of using the Repository Pattern is that it enables a more modular approach to software development. The application logic layer is separated from the data storage layer, making it easier to test and maintain each component separately. This also makes it possible to reuse the application logic layer with different data storage layers.</p><p>Another benefit of using the Repository Pattern is that it can improve performance by reducing the number of calls to the data storage layer. Since the data access logic is encapsulated within the repository, it is possible to optimize queries and reduce the number of database calls.</p><p>Overall, the Repository Pattern is a useful tool for creating scalable, maintainable, and efficient backend systems. It separates concerns and enables a more modular approach to software development, making it easier to test, maintain, and modify the codebase. It can also improve performance by reducing the number of calls to the data storage layer.</p><h3>Dependency Injection Pattern</h3><p>The Dependency Injection (DI) Pattern is a design pattern that enables the creation of loosely coupled software components. It is used to reduce the coupling between components and improve the flexibility, testability, and maintainability of the code.</p><p>In the Dependency Injection Pattern, dependencies are injected into a component rather than being created within the component. This allows components to be created independently of their dependencies, making it easier to replace or modify dependencies without affecting the component itself.</p><p>There are three main types of Dependency Injection: Constructor Injection, Property Injection, and Method Injection.</p><p>Constructor Injection involves passing dependencies to a component through its constructor. Property Injection involves setting dependencies through public properties of the component. Method Injection involves passing dependencies to methods of the component.</p><p>One of the main advantages of using the Dependency Injection Pattern is that it improves the testability of the code. By injecting dependencies into a component, it is possible to create unit tests that isolate the component from its dependencies, making it easier to test the component in isolation.</p><p>Another benefit of using the Dependency Injection Pattern is that it makes the code more flexible and maintainable. By reducing the coupling between components, it is easier to modify or replace components without affecting the rest of the application.</p><p>Overall, the Dependency Injection Pattern is a useful tool for creating scalable, maintainable, and efficient backend systems. It reduces the coupling between components and improves the flexibility, testability, and maintainability of the code.</p><h3>Observer Pattern</h3><p>The Observer Pattern is a design pattern that allows an object (the subject) to notify other objects (the observers) when its state changes. It provides a way for objects to communicate with each other without having direct knowledge of each other’s existence.</p><p>In the Observer Pattern, the subject maintains a list of observers and notifies them when its state changes. The observers can then take action based on the change in the subject’s state. This allows for a loosely coupled relationship between the subject and observers, making it easier to modify or extend the system.</p><p>One of the main advantages of using the Observer Pattern is that it improves the modularity and flexibility of the code. By separating the subject and observers, it is possible to add or remove observers without affecting the subject, or add new subjects without affecting the existing observers.</p><p>Another benefit of using the Observer Pattern is that it can improve the performance of the system. By notifying only the observers that are interested in the change, it is possible to reduce the number of notifications and improve the overall performance of the system.</p><p>Overall, the Observer Pattern is a useful tool for creating scalable, maintainable, and efficient backend systems. It allows for a loosely coupled relationship between objects, improving the modularity and flexibility of the code. It can also improve the performance of the system by reducing the number of notifications.</p><h3>Decorator Pattern</h3><p>The Decorator Pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. It is used to add functionality to objects at runtime, instead of at compile time.</p><p>In the Decorator Pattern, a decorator class is used to wrap the original object. The decorator class has the same interface as the original object, allowing it to be used in the same way. The decorator class then adds behavior to the original object by delegating some of its work to the wrapped object and adding its own behavior.</p><p>One of the main advantages of using the Decorator Pattern is that it allows for the dynamic addition of functionality to objects. This can be useful in situations where the behavior of an object needs to be changed at runtime, or where the behavior of an object needs to be extended without changing its interface.</p><p>Another benefit of using the Decorator Pattern is that it can improve the maintainability of the code. Since the behavior of the object is separated into individual decorators, it is easier to modify or extend the behavior of the object without affecting other parts of the system.</p><p>Overall, the Decorator Pattern is a useful tool for creating scalable, maintainable, and efficient backend systems. It allows for the dynamic addition of functionality to objects, improving the flexibility and maintainability of the code.</p><h3>Real-world Examples of Design Patterns in Backend Development</h3><p>In this section, we’ll explore some real-world examples of how design patterns can be used in backend development.</p><p>Design patterns are a powerful tool that can help developers create scalable, maintainable, and efficient systems. By using design patterns, developers can reuse existing solutions to common problems, reducing development time and improving the quality of the code.</p><p>In this section, we’ll look at some examples of how design patterns are used in popular backend frameworks, including Express.js and Django. We’ll explore how these frameworks use design patterns to solve common problems, and how developers can apply these patterns in their own projects.</p><p>So, let’s dive in and explore some real-world examples of design patterns in backend development.</p><h3>Example of using the MVC pattern in a web application</h3><p>First, we’ll look at an example of using the MVC pattern in a web application with the popular Node.js framework, Express.js.</p><p>In an Express.js application, the Model component is often implemented using a database such as MongoDB or MySQL. The View component is usually implemented using templating engines such as EJS or Handlebars. The Controller component is implemented using middleware functions, which are functions that are executed in a specific order when a request is made to the server.</p><p>For example, when a user requests to view a blog post, the request is handled by the Controller component. The Controller retrieves the blog post from the Model component and passes it to the View component, which renders it using a templating engine. The resulting HTML is then sent back to the user’s browser.</p><p>Using the MVC pattern in a web application can provide several benefits, including improved scalability, maintainability, and testability. By separating the application into distinct components, developers can make changes to one component without affecting the others. This can make it easier to maintain and test the application over time.</p><p>In the following example, the Model is represented by the PostModel class, which is responsible for fetching and saving data to a database.</p><p>The View is represented by the PostView class, which is responsible for rendering the HTML page and handling user input.</p><p>The Controller is represented by the PostController class, which acts as an intermediary between the Model and View. It initializes the View, handles user input, and updates the View based on changes to the Model.</p><pre>// the model<br>interface Post {<br>  id: number;<br>  title: string;<br>  content: string;<br>  date: Date;<br>}<br><br>class PostModel {<br>  private posts: Post[] = [];<br><br>  getPosts() {<br>    // fetch posts from database<br>    return this.posts;<br>  }<br><br>  addPost(post: Post) {<br>    // save post to database<br>    this.posts.push(post);<br>  }<br>}</pre><pre>// the view<br>class PostView {<br>  displayPosts(posts: Post[]) {<br>    // render posts to the HTML page<br>  }<br><br>  getPostFromInput(): Post {<br>    // retrieve input values from the HTML page<br>    // and create a new Post object<br>  }<br>}</pre><pre>// the controller<br>class PostController {<br>  private model: PostModel;<br>  private view: PostView;<br><br>  constructor(model: PostModel, view: PostView) {<br>    this.model = model;<br>    this.view = view;<br>  }<br><br>  init() {<br>    // initialize the view<br>    this.view.displayPosts(this.model.getPosts());<br>  }<br><br>  addPost() {<br>    // get new post from view<br>    const post = this.view.getPostFromInput();<br>    // add post to model<br>    this.model.addPost(post);<br>    // update view<br>    this.view.displayPosts(this.model.getPosts());<br>  }<br>}</pre><p>This implementation of the MVC pattern allows for separation of concerns and modularity in the web application code, making it easier to maintain and scale over time.</p><h3>Example of using the Repository pattern with a database</h3><p>In the Repository pattern, the database is represented as a collection of objects, with each object representing a table or collection in the database. The Repository class provides a set of methods for interacting with the database, such as creating, reading, updating, and deleting objects.</p><p>For example, suppose we have an Express application that stores information about books in a database. We can create a Book model that defines the fields and behavior of a book object. We can then create a BookRepository class that provides methods for creating, reading, updating, and deleting book objects in the database.</p><p>In the BookRepository class, we can define methods such as get_all_books and get_book_by_id that retrieve book objects from the database. We can also define methods such as create_book and update_book that add or modify book objects in the database.</p><p>Using the Repository pattern with a database can provide a number of benefits, including improved testability, maintainability, and flexibility.</p><p>By abstracting the database access layer from the rest of the application, developers can easily switch between different database technologies or change the database schema without affecting the rest of the application. Also, by providing a set of methods for interacting with the database, the Repository pattern can make it easier to write tests for the application.</p><p>In the following example, we define a Book interface that represents a book object with an ID, title, author, and published date. We also define a BookRepository class that provides methods for interacting with a database of books, using a database connection object to execute SQL queries.</p><p>We then demonstrate how to use the BookRepository class to perform common CRUD operations on the database, including getting all books, getting a book by its ID, creating a new book, updating an existing book, and deleting a book.</p><pre>// Define a Book interface that represents a book object<br>interface Book {<br>  id: number;<br>  title: string;<br>  author: string;<br>  publishedDate: Date;<br>}<br><br>// Define a BookRepository class that provides methods for interacting with a database of books<br>class BookRepository {<br>  private db: any; // Database connection object<br><br>  constructor(db: any) {<br>    this.db = db;<br>  }<br><br>  // Get all books from the database<br>  async getAllBooks(): Promise&lt;Book[]&gt; {<br>    const result = await this.db.query(&#39;SELECT * FROM books&#39;);<br>    return result.rows;<br>  }<br><br>  // Get a book by its ID<br>  async getBookById(id: number): Promise&lt;Book&gt; {<br>    const result = await this.db.query(&#39;SELECT * FROM books WHERE id = $1&#39;, [id]);<br>    return result.rows[0];<br>  }<br><br>  // Create a new book in the database<br>  async createBook(book: Book): Promise&lt;void&gt; {<br>    await this.db.query(&#39;INSERT INTO books (title, author, published_date) VALUES ($1, $2, $3)&#39;, [book.title, book.author, book.publishedDate]);<br>  }<br><br>  // Update an existing book in the database<br>  async updateBook(id: number, book: Book): Promise&lt;void&gt; {<br>    await this.db.query(&#39;UPDATE books SET title = $1, author = $2, published_date = $3 WHERE id = $4&#39;, [book.title, book.author, book.publishedDate, id]);<br>  }<br><br>  // Delete a book from the database<br>  async deleteBook(id: number): Promise&lt;void&gt; {<br>    await this.db.query(&#39;DELETE FROM books WHERE id = $1&#39;, [id]);<br>  }<br>}<br><br>// Example usage of the BookRepository class<br>const db = new Database(); // Instantiate a database connection object<br>const bookRepository = new BookRepository(db); // Instantiate a BookRepository object<br>const books = await bookRepository.getAllBooks(); // Get all books from the database<br>const book = await bookRepository.getBookById(1); // Get a book by its ID<br>const newBook = { title: &#39;New Book&#39;, author: &#39;Jane Doe&#39;, publishedDate: new Date() };<br>await bookRepository.createBook(newBook); // Create a new book in the database<br>await bookRepository.updateBook(1, { title: &#39;Updated Book&#39;, author: &#39;John Smith&#39;, publishedDate: new Date() }); // Update an existing book in the database<br>await bookRepository.deleteBook(1); // Delete a book from the database</pre><h3>Example of using the Dependency Injection pattern for decoupling dependencies</h3><p>In the context of backend development, we can use Dependency Injection to decouple our application’s components from the specific implementation of external services or libraries, such as databases, caches, or email providers. This allows us to easily switch between different implementations of these services, or to mock them during testing.</p><p>Here’s an example of using Dependency Injection in a TypeScript application that interacts with a database:</p><pre>// Define an interface for a database connection object<br>interface DatabaseConnection {<br>  query(sql: string, params?: any[]): Promise&lt;any&gt;;<br>}<br><br>// Define a class for a PostgreSQL database connection<br>class PostgresConnection implements DatabaseConnection {<br>  private client: any; // PostgreSQL client object<br><br>  constructor() {<br>    this.client = new PostgreSQLClient(); // Instantiate a PostgreSQL client object<br>    this.client.connect(); // Connect to the database<br>  }<br><br>  async query(sql: string, params?: any[]): Promise&lt;any&gt; {<br>    const result = await this.client.query(sql, params);<br>    return result.rows;<br>  }<br>}<br><br>// Define a class for a BookService that depends on a database connection<br>class BookService {<br>  private db: DatabaseConnection; // Database connection object<br><br>  constructor(db: DatabaseConnection) {<br>    this.db = db;<br>  }<br><br>  async getAllBooks(): Promise&lt;Book[]&gt; {<br>    const result = await this.db.query(&#39;SELECT * FROM books&#39;);<br>    return result.map((row: any) =&gt; ({ id: row.id, title: row.title, author: row.author, publishedDate: row.published_date }));<br>  }<br><br>  async getBookById(id: number): Promise&lt;Book&gt; {<br>    const result = await this.db.query(&#39;SELECT * FROM books WHERE id = $1&#39;, [id]);<br>    return { id: result.id, title: result.title, author: result.author, publishedDate: result.published_date };<br>  }<br><br>  async createBook(book: Book): Promise&lt;void&gt; {<br>    await this.db.query(&#39;INSERT INTO books (title, author, published_date) VALUES ($1, $2, $3)&#39;, [book.title, book.author, book.publishedDate]);<br>  }<br><br>  async updateBook(id: number, book: Book): Promise&lt;void&gt; {<br>    await this.db.query(&#39;UPDATE books SET title = $1, author = $2, published_date = $3 WHERE id = $4&#39;, [book.title, book.author, book.publishedDate, id]);<br>  }<br><br>  async deleteBook(id: number): Promise&lt;void&gt; {<br>    await this.db.query(&#39;DELETE FROM books WHERE id = $1&#39;, [id]);<br>  }<br>}<br><br>// Example usage of the BookService class with a PostgresConnection object<br>const db = new PostgresConnection(); // Instantiate a PostgresConnection object<br>const bookService = new BookService(db); // Instantiate a BookService object with the PostgresConnection object as its dependency<br>const books = await bookService.getAllBooks(); // Get all books from the database<br>const book = await bookService.getBookById(1); // Get a book by its ID<br>const newBook = { title: &#39;New Book&#39;, author: &#39;Jane Doe&#39;, publishedDate: new Date() };<br>await bookService.createBook(newBook); // Create a new book in the database<br>await bookService.updateBook(1, { title: &#39;Updated Book&#39;, author: &#39;John Smith&#39;, publishedDate: new Date() }); //</pre><h3>Example of using the Observer pattern for event-driven programming</h3><p>Suppose we have a web application that allows users to subscribe to different topics of interest. Whenever new content is added to a subscribed topic, the user receives a notification. We can implement this feature using the Observer pattern.</p><p>First, we define our subject interface Topic, which will notify its observers (subscribers) of any updates:</p><pre>interface Topic {<br>  subscribe(observer: Observer): void;<br>  unsubscribe(observer: Observer): void;<br>  notify(): void;<br>}</pre><p>Then we implement the Topic interface in a concrete subject class, TopicManager, which manages a list of subscribers and notifies them whenever new content is added:</p><pre>class TopicManager implements Topic {<br>  private subscribers: Observer[] = [];<br><br>  public subscribe(observer: Observer): void {<br>    this.subscribers.push(observer);<br>  }<br><br>  public unsubscribe(observer: Observer): void {<br>    const index = this.subscribers.indexOf(observer);<br>    if (index !== -1) {<br>      this.subscribers.splice(index, 1);<br>    }<br>  }<br><br>  public notify(): void {<br>    for (const subscriber of this.subscribers) {<br>      subscriber.update();<br>    }<br>  }<br><br>  public addContent(topic: string, content: string): void {<br>    // Add new content to the topic<br>    // ...<br><br>    // Notify all subscribers of the new content<br>    this.notify();<br>  }<br>}</pre><p>Next, we define our observer interface Observer, which has an update a method that will be called by the subject:</p><pre>interface Observer {<br>  update(): void;<br>}</pre><p>We then implement the Observer interface in a concrete observer class, User, which receives notifications when new content is added to a subscribed topic:</p><pre>class User implements Observer {<br>  private readonly username: string;<br><br>  constructor(username: string) {<br>    this.username = username;<br>  }<br><br>  public update(): void {<br>    console.log(`[${this.username}] New content has been added to a subscribed topic`);<br>  }<br>}</pre><p>Finally, we can use our TopicManager and User classes to implement our subscription feature:</p><pre>// Create a new topic manager<br>const topicManager = new TopicManager();<br><br>// Create two users<br>const user1 = new User(&quot;Alice&quot;);<br>const user2 = new User(&quot;Bob&quot;);<br><br>// Subscribe the users to a topic<br>topicManager.subscribe(user1);<br>topicManager.subscribe(user2);<br><br>// Add new content to the topic<br>topicManager.addContent(&quot;science&quot;, &quot;New scientific discovery!&quot;);<br><br>// Output:<br>// [Alice] New content has been added to a subscribed topic<br>// [Bob] New content has been added to a subscribed topic</pre><p>In this example, the TopicManager acts as the subject and the User class acts as the observer.</p><p>The TopicManager maintains a list of subscribers and notifies them whenever new content is added to a subscribed topic. The User class receives notifications and performs some actions, such as displaying a notification to the user.</p><p>The Observer pattern allows us to decouple the subject and observers, making it easy to add or remove subscribers without affecting the rest of the system.</p><h3>Example of using the Decorator pattern for adding functionality to a class dynamically</h3><p>Suppose we have a class Car that represents a basic car with some properties and methods:</p><pre>class Car {<br>  private make: string;<br>  private model: string;<br>  private year: number;<br>  private price: number;<br><br>  constructor(make: string, model: string, year: number, price: number) {<br>    this.make = make;<br>    this.model = model;<br>    this.year = year;<br>    this.price = price;<br>  }<br><br>  public getMake(): string {<br>    return this.make;<br>  }<br><br>  public getModel(): string {<br>    return this.model;<br>  }<br><br>  public getYear(): number {<br>    return this.year;<br>  }<br><br>  public getPrice(): number {<br>    return this.price;<br>  }<br>}</pre><p>We want to add some additional functionality to this class, such as the ability to calculate the sales tax on the car price and to add some optional features to the car, such as a navigation system and a sunroof. We can use the Decorator pattern to add these features dynamically to the Car class.</p><p>First, we define an abstract base class CarFeature that all decorators will inherit from:</p><pre>abstract class CarFeature extends Car {<br>  protected car: Car;<br><br>  constructor(car: Car) {<br>    super(car.getMake(), car.getModel(), car.getYear(), car.getPrice());<br>    this.car = car;<br>  }<br><br>  public abstract getPrice(): number;<br>}</pre><p>Next, we implement concrete decorator classes that add the desired functionality to the Car class:</p><pre>class SalesTaxDecorator extends CarFeature {<br>  public getPrice(): number {<br>    return this.car.getPrice() * 1.10; // 10% sales tax<br>  }<br>}<br><br>class NavigationDecorator extends CarFeature {<br>  public getPrice(): number {<br>    return this.car.getPrice() + 1500; // add $1500 for navigation system<br>  }<br>}<br><br>class SunroofDecorator extends CarFeature {<br>  public getPrice(): number {<br>    return this.car.getPrice() + 1000; // add $1000 for sunroof<br>  }<br>}</pre><p>We can then use these decorators to add functionality to a Car object dynamically:</p><pre>// Create a basic car<br>const car = new Car(&quot;Honda&quot;, &quot;Accord&quot;, 2022, 25000);<br><br>// Add sales tax to the car<br>const carWithSalesTax = new SalesTaxDecorator(car);<br><br>// Add a navigation system to the car<br>const carWithNavigation = new NavigationDecorator(carWithSalesTax);<br><br>// Add a sunroof to the car<br>const carWithSunroof = new SunroofDecorator(carWithNavigation);<br><br>console.log(`Make: ${carWithSunroof.getMake()}`);<br>console.log(`Model: ${carWithSunroof.getModel()}`);<br>console.log(`Year: ${carWithSunroof.getYear()}`);<br>console.log(`Price: ${carWithSunroof.getPrice()}`);<br><br>// Output:<br>// Make: Honda<br>// Model: Accord<br>// Year: 2022<br>// Price: 28750</pre><p>In this example, we use the Decorator pattern to add functionality to a Car object dynamically. Each decorator extends the CarFeature abstract class and adds some additional functionality to the Car object.</p><p>We can add multiple decorators to a Car object in any order, and each decorator adds its own functionality to the object. This allows us to create highly customized Car objects with only the features we need while keeping the core Car class simple and easy to maintain.</p><h3>Conclusion</h3><p>Design patterns are essential in modern backend development as they provide a structured approach to solving common problems. The use of design patterns offers numerous advantages, including code reusability, scalability, maintainability, reduced errors, and improved performance.</p><p>In this tutorial, we discussed some of the most common design patterns used in backend development, including MVC, Repository, Dependency Injection, Observer, and Decorator. We have also provided real-world examples of these patterns in action, along with code samples in TypeScript.</p><p>By understanding and implementing these patterns in their development work, developers can write maintainable, scalable, and efficient code that can easily adapt to changing requirements.</p><p>Overall, the use of design patterns in backend development is essential for creating high-quality, robust applications that can withstand the test of time.</p><h3>Next Steps</h3><p>If you are a backend developer looking to master design patterns, there are several steps you can take to improve your knowledge and skills:</p><ol><li>Read books and articles on design patterns: There are numerous books and articles available on design patterns, and reading them can help you understand the concepts and principles behind them (I have pinned some of them in the next section).</li><li>Practice implementing design patterns: Implementing design patterns in your day-to-day work is the best way to learn them. Start by incorporating one or two patterns into your projects and gradually work your way up to more complex patterns.</li><li>Keep learning: Design patterns are not a one-time thing — they are continually evolving. To stay up-to-date with the latest patterns and best practices, you need to keep learning and experimenting.</li><li>Join online communities: There are many online communities where developers discuss design patterns and share their knowledge and experience. Joining these communities can be a great way to learn from others and to ask for help when you need it.</li><li>Attend workshops and conferences: Attending workshops and conferences focused on design patterns can provide a deep understanding of how they work and how to implement them effectively.</li></ol><p>By following these steps, you can become an expert in design patterns and write high-quality, maintainable, and scalable code for your backend applications.</p><h3>Resources</h3><ol><li>“Design Patterns: Elements of Reusable Object-Oriented Software” by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides</li><li>“Head First Design Patterns” by Eric Freeman, Elisabeth Robson, Bert Bates, and Kathy Sierra</li><li>“Clean Code: A Handbook of Agile Software Craftsmanship” by Robert C. Martin</li><li>“Dependency Injection: Principles, Practices, and Patterns” by Steven van Deursen and Mark Seemann</li><li><a href="https://www.freecodecamp.org/news/the-basic-design-patterns-all-developers-need-to-know/">Three Types of Design Patterns All Devs Should Know</a></li><li><a href="https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application">The Repository Pattern from the Microsoft Docs</a></li><li><a href="https://levelup.gitconnected.com/design-patterns-decorator-pattern-in-typescript-ae899692ac05">Decorator Pattern in TypeScript</a></li><li><a href="https://learn.microsoft.com/en-us/archive/msdn-magazine/2001/july/design-patterns-solidify-your-csharp-application-architecture-with-design-patterns">The Benefits of Using Design Patterns in Software Development</a></li></ol><h3>Stackademic</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77221614c2bb" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/modern-backend-development-a-guide-to-design-patterns-with-practical-examples-77221614c2bb">Modern Backend Development: A Guide to Design Patterns with Practical Examples</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a Secure NestJS Webhook with Payload Validation and Packaging as a Dependency]]></title>
            <link>https://medium.com/@moiserushanika2006/implementing-a-secure-nestjs-webhook-with-payload-validation-and-packaging-as-a-dependency-548b5b73dfb0?source=rss-8dd0bd4ca9c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/548b5b73dfb0</guid>
            <category><![CDATA[webhooks]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[npm]]></category>
            <dc:creator><![CDATA[Moise rushanika]]></dc:creator>
            <pubDate>Thu, 18 Jan 2024 22:15:35 GMT</pubDate>
            <atom:updated>2024-01-18T22:15:35.065Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQHjRF9ajRw4IGsN87kO3Q.png" /></figure><p>If you’ve ever worked on web application development, the term “webhook” has likely crossed your path. The rise of multiple web applications and service integrations has made webhooks increasingly popular. However, it might not always be clear what a webhook is. This article aims to clarify the concept and guide you through implementing a secure NestJS webhook with payload validation. Additionally, we’ll explore the important practice of validating webhook deliveries.</p><h3>Understanding Webhooks</h3><p>In the realm of web application development, a web API typically acts as a “server” that waits to receive requests from a “client.” However, webhooks operate differently. They serve as a mechanism for enabling communication between web applications by sending information when specific events occur. Webhooks, sometimes referred to as “reverse APIs,” initiate communication by sending information to other applications, making them efficient for real-time notifications and data updates.</p><p>Some common use cases for webhooks include syncing customer data in other applications like CRMs, notifying a courier company to collect a product after an online purchase, and sending data to external data analysis services.</p><h3>How to Implement a Secure Webhook in NestJS</h3><p>Let’s dive into the process of implementing a webhook on top of a web API using NestJS, a popular Node.js framework. We’ll also incorporate payload validation to ensure the security of the communication.</p><h3>Step 1: Create a Webhook Handler Module</h3><p>Start by creating a new module dedicated to the webhook handler using the NestJS CLI:</p><pre>nest generate module webhook-handler</pre><h3>Step 2: Define the Webhook Handler Interface</h3><p>Create an interface to define the structure of the webhook handler. This will allow users of the module to implement their own handlers for specific events.</p><pre>// src/webhook-handler/webhook-handler.interface.ts<br><br>export interface WebhookHandler {<br>  handleWebhook(payload: any): Promise&lt;void&gt;;<br>}</pre><h3>Step 3: Implement the Webhook Handler Service</h3><p>Develop a service within the webhook-handler module to handle webhook events.</p><pre>// src/webhook-handler/webhook-handler.service.ts<br><br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { WebhookHandler } from &#39;./webhook-handler.interface&#39;;<br><br>@Injectable()<br>export class WebhookHandlerService implements WebhookHandler {<br>  async handleWebhook(payload: any): Promise&lt;void&gt; {<br>    // Implement your webhook handling logic here<br>    console.log(&#39;Received webhook payload:&#39;, payload);<br>    // Add your custom logic here<br>  }<br>}</pre><h3>Step 4: Implement the Webhook Handler Controller</h3><p>Create a controller within the webhook-handler module to handle incoming webhook payloads.</p><pre>// src/webhook-handler/webhook-handler.controller.ts<br><br>import { Controller, Post, Body } from &#39;@nestjs/common&#39;;<br>import { WebhookHandler } from &#39;./webhook-handler.interface&#39;;<br><br>@Controller(&#39;webhook-handler&#39;)<br>export class WebhookHandlerController {<br>  constructor(private readonly webhookHandler: WebhookHandler) {}<br><br>  @Post()<br>  async handleWebhook(@Body() payload: any): Promise&lt;string&gt; {<br>    try {<br>      await this.webhookHandler.handleWebhook(payload);<br>    } catch (err) {<br>      console.error(&#39;Webhook handler error:&#39;, err.message);<br>      return &#39;Webhook Handler Error&#39;;<br>    }<br><br>    return &#39;Webhook received successfully&#39;;<br>  }<br>}</pre><h3>Step 5: Export the Webhook Handler Module</h3><p>Ensure that the WebhookHandler interface, the WebhookHandlerService, and the WebhookHandlerController are exported from the webhook-handler module.</p><pre>// src/webhook-handler/webhook-handler.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { WebhookHandlerController } from &#39;./webhook-handler.controller&#39;;<br>import { WebhookHandlerService } from &#39;./webhook-handler.service&#39;;<br><br>@Module({<br>  controllers: [WebhookHandlerController],<br>  providers: [WebhookHandlerService],<br>})<br>export class WebhookHandlerModule {}</pre><h3>Step 6: Validate Webhook Deliveries</h3><p>Now, let’s enhance the webhook implementation by incorporating payload validation. GitHub recommends using a secret token to verify that a webhook delivery is from GitHub and hasn’t been tampered with. Here’s how to do it:</p><h4>Step 6.1: Create a Secret Token</h4><p>Create a secret token for your webhook. This can be done when creating a new webhook or by adding a secret token to an existing one. Choose a random string with high entropy.</p><h4>Step 6.2: Store the Secret Token Securely</h4><p>After creating the secret token, store it in a secure location that your server can access. Avoid hardcoding the token into your application or pushing it to any repository.</p><h4>Step 6.3: Validate Incoming Webhook Payloads</h4><p>GitHub will use your secret token to create a hash signature sent with each payload. This signature will appear in each delivery as the value of the X-Hub-Signature-256 header.</p><p>In your code handling webhook deliveries, calculate a hash using your secret token. Compare the calculated hash with the hash GitHub sent and ensure they match. Use secure comparison methods to mitigate certain timing attacks.</p><h4>Step 6.4: Testing the Webhook Payload Validation</h4><p>You can use the following secret and payload values to verify your implementation:</p><ul><li>Secret: “It’s a Secret to Everybody”</li><li>Payload: “Hello, World!”</li></ul><p>If your implementation is correct, the signatures you generate should match the provided signature values.</p><pre>Signature: 757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17<br>X-Hub-Signature-256: sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17</pre><h3>Step 7: Integrate Webhook Modules into the Main Application</h3><p>Update your main application module (app.module.ts) to import the WebhookHandlerModule.</p><pre>// app.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { WebhookHandlerModule } from &#39;./webhook-handler/webhook-handler.module&#39;;<br><br>@Module({<br>  imports: [WebhookHandlerModule],<br>})<br>export class AppModule {}</pre><h3>Step 8: Run the Application</h3><p>Now, let’s run the application:</p><pre>npm run start:dev</pre><h3>Step 9: Test the Webhooks</h3><p>Finally, test that the webhooks are called correctly. Use tools like Postman or cURL to make requests to your webhook endpoints.</p><p>For the generic webhook:</p><pre>POST /webhook-handler HTTP/1.1<br>Host: localhost:3000<br>Content-Type: application/json<br>Content-Length: &lt;length&gt;<br> <br>{<br>    &quot;someData&quot;: &quot;example&quot;<br>}</pre><p>Check the console logs to see the webhook payloads being received and processed.</p><h3>Step 10: Implementing Payload Validation</h3><p>Now, let’s modify our NestJS application to incorporate GitHub’s recommended payload validation with a secret token.</p><h4>Step 10.1: Install Necessary Packages</h4><p>Install the crypto package, which will be used for HMAC verification:</p><pre>npm install crypto</pre><h4>Step 10.2: Update Webhook Handler Service</h4><p>Update the WebhookHandlerService to include payload validation:</p><pre>// src/webhook-handler/webhook-handler.service.ts<br><br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { WebhookHandler } from &#39;./webhook-handler.interface&#39;;<br>import * as crypto from &#39;crypto&#39;;<br><br>@Injectable()<br>export class WebhookHandlerService implements WebhookHandler {<br>  private readonly secretToken = &#39;It\&#39;s a Secret to Everybody&#39;; // Replace with your actual secret token<br><br>  async handleWebhook(payload: any, signature: string): Promise&lt;void&gt; {<br>    // Validate the payload using the secret token<br>    if (!this.validatePayload(payload, signature)) {<br>      throw new Error(&#39;Webhook payload validation failed&#39;);<br>    }<br><br>    // Continue with your webhook handling logic<br>    console.log(&#39;Received and validated webhook payload:&#39;, payload);<br>    // Add your custom logic here<br>  }<br><br>  private validatePayload(payload: any, signature: string): boolean {<br>    const expectedSignature = &#39;sha256=&#39; + crypto<br>      .createHmac(&#39;sha256&#39;, this.secretToken)<br>      .update(JSON.stringify(payload))<br>      .digest(&#39;hex&#39;);<br><br>    // Use secure comparison to mitigate timing attacks<br>    return crypto.timingSafeEqual(<br>      Buffer.from(expectedSignature, &#39;ascii&#39;),<br>      Buffer.from(signature, &#39;ascii&#39;)<br>    );<br>  }<br>}</pre><h4>Step 10.3: Update Webhook Handler Controller</h4><p>Update the WebhookHandlerController to include the signature in the request headers:</p><pre>// src/webhook-handler/webhook-handler.controller.ts<br><br>import { Controller, Post, Body, Headers } from &#39;@nestjs/common&#39;;<br>import { WebhookHandler } from &#39;./webhook-handler.interface&#39;;<br><br>@Controller(&#39;webhook-handler&#39;)<br>export class WebhookHandlerController {<br>  constructor(private readonly webhookHandler: WebhookHandler) {}<br><br>  @Post()<br>  async handleWebhook(@Body() payload: any, @Headers(&#39;x-hub-signature-256&#39;) signature: string): Promise&lt;string&gt; {<br>    try {<br>      await this.webhookHandler.handleWebhook(payload, signature);<br>    } catch (err) {<br>      console.error(&#39;Webhook handler error:&#39;, err.message);<br>      return &#39;Webhook Handler Error&#39;;<br>    }<br><br>    return &#39;Webhook received and validated successfully&#39;;<br>  }<br>}</pre><h3>Packaging as a Dependency</h3><p>Now that we have a functional webhook module, you may want to package it as a standalone dependency for reuse across multiple projects. Here’s how you can achieve that:</p><h4>Step 11.1: Create a Package Configuration</h4><p>Create a package.json file in the root of your webhook-handler module directory. Specify the package name, version, and other relevant information.</p><pre>// webhook-handler/package.json<br><br>{<br>  &quot;name&quot;: &quot;@your-username/webhook-handler&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;main&quot;: &quot;dist/index.js&quot;,<br>  &quot;types&quot;: &quot;dist/index.d.ts&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;tsc&quot;,<br>    &quot;prepublishOnly&quot;: &quot;npm run build&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@nestjs/cli&quot;: &quot;^x.x.x&quot;,<br>    &quot;@nestjs/core&quot;: &quot;^x.x.x&quot;,<br>    &quot;typescript&quot;: &quot;^x.x.x&quot;,<br>    &quot;reflect-metadata&quot;: &quot;^x.x.x&quot;,<br>    &quot;ts-node&quot;: &quot;^x.x.x&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;@nestjs/common&quot;: &quot;^x.x.x&quot;<br>    // ... your other dependencies here if needed<br>  }<br>}</pre><p>Make sure to replace @your-username/webhook-handler with a unique package scope and name.</p><h4>Step 11.2: Create a Build Script</h4><p>Add a build script to compile your TypeScript code into JavaScript. Update the scripts section in package.json:</p><pre>// webhook-handler/package.json<br><br>&quot;scripts&quot;: {<br>  &quot;build&quot;: &quot;tsc&quot;,<br>  &quot;prepublishOnly&quot;: &quot;npm run build&quot;<br>}</pre><h4>Step 11.3: Compile the TypeScript Code</h4><p>Run the build script to compile the TypeScript code into JavaScript:</p><pre>cd webhook-handler<br>npm install<br>npm run build</pre><h4>Step 11.4: Publish the Package</h4><p>Publish the package to a package registry (e.g., npm):</p><pre>npm login<br>npm publish --access public</pre><p>Now, your webhook handler module is published as a standalone package and can be installed in other NestJS projects using:</p><pre>npm install @your-username/webhook-handler</pre><h3>Conclusion</h3><p>By following these steps, you’ve successfully implemented a secure NestJS webhook with payload validation and packaged it as a reusable dependency. This approach ensures that your webhook only processes deliveries from GitHub and avoids potential man-in-the-middle attacks. Always prioritize security when dealing with webhooks, especially when handling sensitive information or integrations with external services.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=548b5b73dfb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>