Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

List of all questions

Total questions: 360
Total unique questions: 260

bullshit_everywhere_meme

Python

  • Can we have multiple inheritance in Python? What is the algorithm behind it? (5 times — Digikala, Itoll, Ozone, Snapp (cab 1), Zibal)

    Answer

    Inheritance models an ‘is-a’ relationship and shares behavior via a superclass. Composition models ‘has-a’ and embeds functionality by using other objects. Composition is generally preferred for flexibility and testability.

  • What is decorator? (6 times — 2x Digikala, Exalab, Karnameh, Siz-tel, Sternx)

  • What is the difference between concurrency in python and go? (2 times — Quiz of Kings, Narvan)

  • What is mutable and immutable and why? give me an example for each. (3 times — 2x Exalab, Snapp (cab 2))

  • What is generator? when do we use them? do you use them? (3 times — Exalab, Karnameh, Zibal)

    Answer

    A generator is a function that yields values lazily and returns an iterator. Benefits: low memory usage for large sequences, simple stateful iteration, and easy composition of pipelines. - Introduction to Python Generators

  • What is middleware in django? (2 times — Narvan, Toman Pay)

  • What is python memory management? (2 times — Narvan, Snappshop)

  • What is the difference between is and == in Python? (2 times — Snappshop, Zibal)

    Answer

    The is operator checks for identity. The == operator checks for equality.

        a = [1, 2, 3]
        b = a     # b references the same list as a
        c = a[:]  # c is a new list with the same content as a
    
        print(a is b)  # True, because b is the same object as a
        print(a is c)  # False, because c is a different object
        print(a == c)  # True, because a and c have the same content
    
  • Which function of async in python can run tasks in background? For example we have 4 request and we want send all of it in one time. (1 times — Digikala)

  • What is list comprehension? (1 times — Digikala)

  • What is python data types? and how do you grouping them? (1 times — Exalab)

  • What is coroutine? (1 times — Exalab)

  • What is the difference between set and list? (1 times — Exalab)

  • What is method overriding in python? (1 times — Itoll)

  • What is GIL? (1 times — Narvan)

  • Compare python with C++. (1 times — Snapp (cab 1))

  • Why are we able to change python tuple values even though they are immutable? (1 times — Snapp (cab 2))

  • What are the differences between Go and Python? Compare these two languages. (1 times — Snappshop)

  • How does referencing work in Python, and how does it determine when to clean up references? (1 times — Snappshop)

  • How does a Python project (django or fastapi) start up? How is it run from scratch? (1 times — Snappshop)

  • In Python, how does a request reach our service? (1 times — Snappshop)

  • Tell me about Django request life-cycle. (1 times — Toman Pay)

  • Can you tell what is the usage of UWSGI/Gunicorn? (1 times — Toman Pay)

  • Can You tell what are the migration files in django? (1 times — Toman Pay)

  • What is the difference between a @classmethod and a @staticmethod? When would you use a @classmethod? (1 times — Zibal)

    Answer

    @classmethod receives the class (cls) and is used for alternative constructors or methods that operate on class-level state. @staticmethod has no implicit first argument and is used for utility functions grouped with the class without accessing class or instance state. realpython

  • How do you create private methods in Python? (1 times — Zibal)

    Answer

    Use a single leading underscore _method to indicate ‘internal’ use (convention). Use double leading underscores __method for name-mangling to reduce accidental access from subclasses; note that nothing is truly private. - Python Private Methods Explained

  • Can you explain Django’s architecture? (1 times — Zibal)

    Answer

    Django follows an MTV (Model–Template–View) pattern: Models hold data/ORM; Views handle requests; Templates render presentation. Requests flow through middleware, URL routing sends them to views, which use models/templates; Django runs on WSGI/ASGI. - Understanding Django’s Architecture: The MTV Pattern

  • What are serializers in Django REST Framework (DRF)? (1 times — Zibal)

    Answer

    Django’s serialization framework provides a mechanism for “translating” Django models into other formats. Usually these other formats will be text-based and used for sending Django data over a wire, but it’s possible for a serializer to handle any format (text-based or not). djangoproject

  • What are custom permissions in DRF and how do you implement them? (1 times — Zibal)

    Answer

    Custom permissions encapsulate business authorization rules. Implement them by subclassing rest_framework.permissions.BasePermission and overriding has_permission and/or has_object_permission, then apply to views or viewsets. - DRF Permissions

  • How can use for example 30 core of cpu in production with python? (1 times — Zibal)

    Answer

    In Python, you scale CPU usage by running multiple processes, not threads. In production I usually run Uvicorn behind Gunicorn and configure it with one worker per CPU core—so on a 30-core machine, -w 30 lets the app fully utilize all cores.

        gunicorn app:app -k uvicorn.workers.UvicornWorker -w 30
    
  • Explain call by reference & call by value. (4 times — Hamkaran System, MH Holding, 2x Narvan)

  • What is abc? (1 times — Digikala)

  • We have one dictionary and we have a function that change this dictionary. If function doesn’t return anything, our dictionary changed or not? (1 times — Exalab)

  • Difference between list & set? Which one is faster? (1 times — Itoll)

Go

  • What is channel? (3 times — Autoshenas, Ozone, Siz-tel)

  • What is goroutine? (2 times — Quiz of Kings, Siz-tel)

  • How many goroutines can you create(open)? (2 times — Doctoreto, Metazi)

    Answer

    Millions are possible, limited by memory (heap + per-goroutine stack) and scheduling overhead. GOMAXPROCS controls parallel workers/OS threads (parallelism), not the total goroutine count. Real limit depends on your workload and memory profile. ardanlabs

  • What is OOP concepts that go don’t have it? (3 times — Hamkaran System, Snapp (cab 1), Sternx)

  • What is defer? (2 times — Hamkaran System, Snapp (cab 2))

  • We have a scenario that we have a goroutine and this goroutine wait for other goroutine how do you handle it? waitgroup. (2 times — MH Holding, Ozone)

  • What’s difference between goroutine and thread? (2 times — Cloudzy, 780)

    Answer
  • What is the difference between pointer receivers and value receivers in Go? (1 times — Cloudzy)

    Answer
  • How do you detect memory leaks in Go? (1 times — Cloudzy)

    Answer

    Using the pprof package to profile memory usage and inspect heap allocations. Observing increasing memory usage over time in long-running programs. Running Go’s race detector (go run -race) to catch goroutine leaks that may indirectly cause memory retention. - Memory Leaks in Go

  • What can happen if goroutines are not properly stopped or cleaned up? (1 times — Cloudzy)

    Answer

    If goroutines aren’t properly stopped, they can leak memory, waste CPU, and potentially cause deadlocks or resource exhaustion in the program.

  • Is there a semaphore concept in Go? (1 times — Doctoreto)

    Answer

    Go has no built-in semaphore type, but a counting semaphore is commonly implemented with a buffered channel or a small wrapper around sync primitives. sync provides low-level primitives; higher-level concurrency is often done with channels.

  • If you had to implement Go channels from scratch, how would you design them? (1 times — Doctoreto)

    Answer

    medium

  • How are goroutines blocked and woken up? Who handles that? (1 times — Doctoreto)

    Answer

    The Go runtime scheduler handles blocking/wakeup. Goroutines are parked when they wait on channels, locks, I/O, timers, or syscalls; the runtime keeps them on wait lists and moves them to runnable queues when the event occurs (timer, channel ready, I/O complete), then schedules them onto OS threads.

  • How can you reduce GC pressure in Go? (1 times — Doctoreto)

    Answer

    Reduce allocations and object lifetimes: reuse buffers, pool temporary objects, use sync.Pool for short-lived objects, avoid unnecessary boxing/heap escapes, prefer stack/value types when safe, batch work to reuse memory. Measure with pprof and trace before optimizing. victoriametrics

  • What is memory complexity when go tries to put our slice to another (big one)? (1 times — Hamkaran System)

  • What is the difference between strings in Go and C? (1 times — Hamkaran System)

  • What is rune and size? (1 times — Hamkaran System)

  • What is UTF-8 and difference with ASCII? What is 8 mean? What is UTF-16? (1 times — Hamkaran System)

  • What is method? (2 times — Hamkaran System, MH Holding)

  • How do we use the encapsulation concept in Go? (1 times — Hamkaran System)

  • What is garbage collector? (2 times — Hamkaran System, 780)

    Answer

    Go’s Garbage Collector (GC) is famously simple from a developer’s perspective (you just let variables fall out of scope), but under the hood, it is a highly sophisticated, modern piece of engineering.

    Its primary design goal is low latency, meaning it aims to keep application pause times as short as possible (typically under 500 microseconds), rather than maximizing overall throughput.

    Here is a breakdown of how Go’s GC works.

    1. The Core Algorithm: Tri-Color Mark-and-Sweep

    gc

    Go uses a concurrent tri-color mark-and-sweep algorithm.

    Imagine every object in memory as a node in a giant web, connected by pointers. The GC’s job is to start at “root” pointers (like global variables and local variables on your CPU stacks) and trace this web to find out what is still alive.

    To do this concurrently without stopping your program, it colors objects three ways:

    • White: The object has not been visited yet. (At the end of the cycle, anything still white is garbage).
    • Grey: The object has been visited, but the GC hasn’t yet checked the pointers inside this object to see what they point to. (Think of grey as the “to-do list”).
    • Black: The object has been visited, and all the objects it points to have been successfully marked grey/black. (This object is definitively alive and fully processed).

    The Rule: A black object must never be allowed to point directly to a white object. If that happens, the white object gets lost and becomes a memory leak.

    2. The Lifecycle of a GC Cycle

    A single GC cycle happens in four distinct phases. Two of these require briefly stopping your program (Stop-The-World, or STW), but they are incredibly fast.

    1. Mark Start (STW - very brief): The GC stops the program just long enough to scan the stacks and global variables. It turns everything those roots point to Grey, and turns the roots themselves Black.
    2. Concurrent Marking (No pause): The GC runs on dedicated background threads. It picks a Grey object, looks at the pointers inside it, and turns the objects it points to Grey. Once finished, it turns the original object Black. It repeats this until there are no Grey objects left. Meanwhile, your application is running normally.
    3. Mark Termination (STW - very brief): The GC stops the program again to clean up. It re-scans any stacks that might have changed during the concurrent phase, clears internal GC state, and prepares for the next step.
    4. Concurrent Sweeping (No pause): The GC runs in the background and walks through the memory pages. Any object that is still White is freed up and returned to the memory pool for future use.

    3. The Magic Trick: The Write Barrier

    If your program is running while the GC is coloring things, what happens if your program suddenly changes a pointer?

    For example: What if the GC just turned Object A Black, and then your program changes Object A to point to a brand new White object? This violates the core rule and means the new object would be mistakenly deleted.

    Go solves this using a Write Barrier. The Go compiler secretly injects a tiny piece of code every time your program writes to a pointer. If the GC is currently in the concurrent marking phase, this write barrier intercepts the assignment. It ensures that if a Black object is forced to point to a White object, the White object is immediately turned Grey (added to the to-do list) so it doesn’t get lost.

    Go specifically uses a Hybrid Write Barrier (introduced in Go 1.8) which drastically reduced the length of the STW pauses by simplifying how stack rescanning works.

    4. What Go’s GC Does NOT Do (Common Misconceptions)

    • No Generational GC: Languages like Java or V8 (JavaScript) use “generational” GCs, assuming that most objects die young (created and destroyed in milliseconds). They split the heap into “Young” and “Old” generations. Go does not do this. Go uses a unified heap. Why? Go’s pointer-heavy structures (like slices and maps) and the way Go code is typically written didn’t show a massive “die young” benefit, and a unified heap is much simpler to implement without introducing latency spikes.
    • No Compaction (Moving objects): Many GCs move surviving objects around in memory to pack them tightly together and prevent fragmentation. Go does not move objects. Once an object is allocated at a memory address, it stays there until it dies. This makes Go’s GC much faster and simpler, but it means memory can become fragmented over time.

    5. How to Control It

    By default, Go triggers a GC cycle when the heap size doubles. You can tweak this using environment variables:

    • GOGC: The default is 100 (meaning 100% growth = doubling). If you set GOGC=200, the heap can grow by 300% before a GC triggers (less frequent GC, but higher memory usage). If you set GOGC=50, it triggers after 50% growth (more frequent GC, lower memory footprint).
    • GOMEMLIMIT (Introduced in Go 1.19): This is a hard upper limit on total memory (heap + off-heap + OS overhead). If Go approaches this limit, it will trigger GC as aggressively as possible to try and stay under the ceiling, preventing your app from being killed by the OS’s Out-Of-Memory (OOM) killer.

    bytebytego

  • When should we use panic? (3 times — 3x Hamkaran System)

  • We have service out of here that panics somewhere and we don’t want panic here because here is more important imagine something like rocket system how can handle this? (1 times — Hamkaran System)

  • What is init in Go? How does it work and how does it differ from main? (1 times — Metazi)

    Answer

    go.dev

      `init()` is a special function: `func init()`. It runs automatically after package-level variables are initialized. You can have multiple `init()`s in a package. You cannot call `init()` yourself.
    
      Order: evaluate package vars → run that package’s `init()`s → repeat by dependency order → finally call `main.main()`.
    
      `main()` is the program entry point (`package main`, `func main()`) and runs once after all `init()`s finish.
    
  • If you have multiple goroutines that fetch data from different APIs and you want to gather all results and aggregate them, or wait with a timeout then aggregate, how can you do this? (1 times — Metazi)

    Answer
        package main
    
        import (
            "fmt"
            "sync"
            "time"
        )
    
        type Result struct {
            URL  string
            Body string
            Err  error
        }
    
        func fetch(url string) (string, error) {
            // do actual HTTP call...
            return "data-for-" + url, nil
        }
    
        func fetchPartial(urls []string, timeout time.Duration) map[string]string {
            var wg sync.WaitGroup
            resultsCh := make(chan Result, len(urls))
    
            for _, u := range urls {
                wg.Add(1)
                go func(u string) {
                    defer wg.Done()
                    body, err := fetch(u)
                    resultsCh <- Result{URL: u, Body: body, Err: err}
                }(u)
            }
    
            // close channel when all goroutines are done
            go func() {
                wg.Wait()
                close(resultsCh)
            }()
    
            aggregated := make(map[string]string)
            timeoutCh := time.After(timeout)
    
        Loop:
            for {
                select {
                case r, ok := <-resultsCh:
                    if !ok {
                        break Loop // channel closed, all responses received
                    }
                    if r.Err == nil {
                        aggregated[r.URL] = r.Body
                    } else {
                        // optionally log r.Err
                    }
                case <-timeoutCh:
                    // timeout occurred — stop waiting for more, but goroutines may still be running.
                    // To avoid leaks in real code, pass a context to requests so they cancel.
                    break Loop
                }
            }
            return aggregated
        }
    
        func main() {
            urls := []string{"a", "b", "c"}
            out := fetchPartial(urls, 2*time.Second)
            fmt.Println(out)
        }
    
  • How does Go manage goroutines? (1 times — Metazi)

    Answer

    The runtime scheduler uses three core concepts: G, M, and P.

      - G (goroutine): the user-level unit of concurrency (stack, state, metadata). Goroutines are cheap to create and their stacks grow and shrink as needed.
      - M (machine): an OS thread that actually executes Go code. The runtime creates and reclaims Ms as needed (e.g., to service blocking syscalls).
      - P (processor): a scheduler context that holds a run queue of runnable Gs and scheduling state. Only an M that has an associated P can run Go code. `GOMAXPROCS` controls how many Ps exist (how many goroutines can run in parallel).
    
      How scheduling works (high level):
    
      - Each P has a local run queue of runnable goroutines. When a goroutine becomes runnable it’s pushed to a P’s queue. When a P runs out of work it will steal goroutines from other Ps or pull from a global queue; this provides locality and load balancing.
      - The scheduler chooses a G from a P’s run queue and runs it on the M bound to that P. If that G blocks (channel wait, sleep, blocking syscall), it is parked and another G is scheduled.
    
  • What is generic? (1 times — MH Holding)

  • We have a scenario. We have two goroutine that traverse a slice. One is start from beginning and other starts from end. How each goroutine can know other one is in the middle of slice? With channels. (1 times — MH Holding)

  • What is context in go? (1 times — MH Holding)

  • Is Golang an OOP language? (1 times — Ozone)

  • What is Mutex? (1 times — Ozone)

  • Tell me about go data types. (1 times — Siz-tel)

  • What is difference between channel and connection in rabbitMQ? (1 times — Snappshop)

  • What is init function? (1 times — MH Holding)

  • What is a slice, and what is the difference between a slice and an array? (2 times — Hamkaran System, Siz-tel)

  • What is Promise? (1 times — Kharazmi)

  • What is stack and differences between heap? (1 times — Hamkaran System)

  • What is _ in imported packages? (1 times — Metazi)

    Answer

    _ is the blank identifier. When used in an import like import _ "pkg/path" it means: import the package solely for its side effects (package initialization) but do not bind any name to refer to it in the importing file. The compiler won’t complain about an unused import because the blank identifier intentionally discards the package name.

        import (
            _ "github.com/lib/pq" // register pq as a database/sql driver via its init()
        )
    
      (Aside: `_` is also used to discard values in assignments: `_, ok := m["x"]`.)
    
  • Why use it? If there is no need, should we remove it? Why do people still use it? (1 times — Metazi)

    Answer

    Use them when the package’s init() performs necessary side effects (driver registration, plugin/handler registration, global initialization). If a package has no needed side effects, remove the import.

  • Why write configs in init instead of main? What are the benefits? What are the problems if we write all code in init instead of main? (1 times — Metazi)

    Answer

    Pros: init() runs before main(), so it can prepare package-level state.

      Cons: `init()` cannot accept `context` or return errors, runs during tests, runs before flag/config parsing, and makes shutdown/signal handling hard. Prefer `main()` for orchestration, lifecycle and graceful shutdown.
    
  • Multiple packages each run an init that Printfs the package name. You import them in main, but main() is empty. What is the output? (1 times — Metazi)

    Answer
        // pkg/a/a.go
        package a
    
        import "fmt"
    
        func init() { fmt.Println("init a") }
    
        // pkg/b/b.go
        package b
    
        import "fmt"
    
        func init() { fmt.Println("init b") }
    
        // main.go
        package main
    
        import (
            _ "example.com/project/pkg/a"
            _ "example.com/project/pkg/b"
        )
    
        func main() {} // empty
    
      Important notes about the order:
    
      - Initialization (and therefore the `init()` prints) runs before `main()` is called.
      - The order between packages follows the import dependency graph: if `b` imports `a`, `init a` will always appear before `init b`.
      - If the packages are independent (neither imports the other), the relative order is unspecified — you should not rely on a particular ordering.
      - `main()` being empty produces no additional output.
    
      Output:
    
        init a
        init b
    
  • When you receive a request, how do you read data? How do you unmarshal it? (1 times — MH Holding)

  • What is anonymous function? (1 times — Siz-tel)

  • If we want to know type of var in runtime, how can figure out? (1 times — Siz-tel)

  • What is buffered and unbuffered channel in Go? (1 times — 780)

    Answer
    • Unbuffered (make(chan T)) has zero capacity and requires both sender and receiver to be ready simultaneously—acting as a synchronous handoff.

    • Buffered (make(chan T, n)) has a fixed queue; senders block only when full, receivers block only when empty—acting as an asynchronous mailbox.

      Unbuffered channels guarantee a synchronization point (safe for signaling), while buffered channels decouple goroutines for higher throughput. Use unbuffered by default for simplicity and safety; use buffered only for known bursts or rate-limiting, and never guess the buffer size without benchmarking.

  • What is a worker pool and what are its benefits? (1 times — 780)

    Answer
    • Bounded resource usage — you control exactly how many things run concurrently (e.g., match DB connection pool size).
    • Backpressure — if the queue fills up, producers slow down or block, instead of the system falling over.
    • Reusability — workers aren’t recreated per task, avoiding goroutine/thread spin-up overhead.
    • Easier to reason about — a known, fixed concurrency level makes load testing and capacity planning predictable.
    • Graceful shutdown — you can close the job channel and sync.WaitGroup.Wait() for a clean drain.

Database

  • How do database index columns work? (5 times — Quiz of Kings, Karnameh, Snapp (cab 2), 2x Snappshop)

  • What is ACID? (6 times — 2x Digikala, Karnameh, MH Holding, Zibal, 780)

    Answer
  • Can you list and explain common database isolation levels and the trade-offs between them? (4 times — Doctoreto, 2x Snappshop, 780)

    Answer

    geeksforgeeks Wikipedia

  • What is the difference between SQL and NoSQL? (3 times — Exalab, Siz-tel, Snapp (cab 2))

  • If our query is slow, how would you optimize it? What is your solution for this problem? (3 times — Hamkaran System, Snappshop, Wallex)

  • If you want to design a database, how do you determine which technologies or approaches to use? (3 times — Quiz of Kings, Digikala, 780)

  • When indexing is bad? (2 times — Snapp (cab 2), Snappshop)

  • What is redis data structures? (1 times — Quiz of Kings)

  • Suppose we have a queue and a redis and more requests sent to our web server how can handle to redis. redis can handle just a few requests. What’s your approach to handle scale? (1 times — Quiz of Kings)

  • Why you used Postgres in your company? What’s difference between Postgres and MySQL? (1 times — Autoshenas)

  • What is hash table? (1 times — Cloudzy)

    Answer

    In computer science, a hash table is a data structure that implements an associative array, also called a dictionary or simply map; an associative array is an abstract data type that maps keys to values. A hash table uses a hash function to compute an index, also called a hash code, into an array of buckets or slots, from which the desired value can be found. During lookup, the key is hashed and the resulting hash indicates where the corresponding value is stored. A map implemented by a hash table is called a hash map. wikipedia

  • Suppose we have an application that we sell it to customer. Now we want change the database of that without changing anything on that application because it’s not backward compatible how can we do that? (1 times — DAA)

  • Suppose we have a social media platform, and we want to retrieve all comments of a post. I am using a for statement for this scenario. Is this approach correct? How would you solve this? (1 times — Digikala)

  • If some service failed in microservice or some database broken, which approach can solve that? (1 times — Digikala)

  • What is eventual consistency in the context of databases and distributed systems? (1 times — Doctoreto)

    Answer

    a replication model where updates will propagate and replicas converge eventually (if no new updates), so reads may be stale briefly but become consistent over time. Practical trade-off: higher availability and latency at the cost of short-term anomalies. Wikipedia

  • What is the difference between WHERE and HAVING in SQL? (1 times — Exalab)

  • Have you experienced with mysql? (1 times — Exalab)

  • Scenario: We have some tables about students, courses and student course. (1 times — Itoll)

  • What is Redis? Why it’s fast? (1 times — Itoll)

  • What are transactions in a database? (1 times — Karnameh)

  • What is NoSql? (1 times — Narvan)

  • mongoDB is a NoSql? (1 times — Narvan)

  • What is LEFT OUTER JOIN? (1 times — Narvan)

  • What is redis data types? (1 times — Siz-tel)

  • What is primary key and foreign key in database? And what’s differences? (1 times — Snapp (cab 1))

  • If you have multiple users with the same password, resulting in identical hashes, and you want to ensure that their records in the database are unique, what can you do to make the records unique? (1 times — Snappshop)

  • We have a table with three fields: start time, end time and ID. This is too slow. How do you try to speed it up? (1 times — Snappshop)

  • What is ORM? (1 times — Wallex)

  • Can you example of some tables with one-to-one one-to-many many-to-many many-to-one? (1 times — Wallex)

  • Consider we have some tables and we have fk in each… // TODO (1 times — Wallex)

  • We have a cache for some data in our exchange that we show on the page to users, such as the number of trades, Tether price, etc. When the cached data is cleared, many requests hit the database directly, causing heavy load and potential downtime. How would you fix this problem? (1 times — Wallgold)

    Answer
    1. Primary Defense: The Mutex Lock with Stale Data Fallback

      This is your immediate and most critical fix. It directly stops the herd.

      How it works: When the cache for a key is found to be empty or expired, the first request to notice it acquires a distributed lock (e.g., in Redis). Only this request is permitted to query the database.

      Handling Subsequent Requests: All other concurrent requests for the same data are not sent to the database. Instead, they have two graceful paths:

      Wait Briefly: They can wait for a short, fixed period (e.g., 50-100ms) for the first request to populate the cache.

      Serve Stale Data (Preferred): Even better, the system immediately returns the recently expired (“stale”) data while the cache is being refreshed in the background. This provides the best user experience—fast responses with near-real-time data.

    2. Proactive Mitigation: Prevent Synchronized Expiration

      The thundering herd is often caused by thousands of cache entries expiring at the same moment.

      Jitter: Never set a fixed TTL (Time-To-Live). Instead, add a small, random value (±10%) to the expiration time. This spreads cache regeneration naturally over a window of time, preventing a synchronized stampede.

      Probabilistic Early Refresh: Before a cache entry officially expires, have a small percentage of requests (e.g., 1%) trigger an early refresh in the background. This “warms” the cache proactively, making it highly likely that a fresh value is already in place before the true expiration time.

    3. Architectural Decoupling: Asynchronous Cache Population

      For the ultimate resilience, decouple the user request from the cache regeneration process entirely.

      How it works: A cache miss never triggers a synchronous database call from a user request. Instead, the system always returns stale data or a default and pushes a “cache refresh task” for that key onto a background job queue (e.g., Redis Queue, SQS, Kafka).

      Benefit: User response times become immune to database performance. The background workers can process the refresh tasks at their own pace, and the database load is smoothed out. This is the most robust long-term pattern for high-throughput systems.

  • How does Django ORM address the N+1 query problem? (1 times — Zibal)

    Answer

    Django provides select_related for single-valued relationships and prefetch_related for many-to-many or reverse relations to eager-load related objects and avoid N+1 queries. You should profile queries and use .values() or annotations when appropriate. - Django ORM Performance Tips (YouTube) - Django Database Optimization - Django QuerySets

  • How can you ensure only one instance of your database adapter is created in Python? (1 times — Zibal)

    Answer

    With singleton pattern

  • What is elasticsearch? (1 times — Autoshenas)

  • Can you write query? (1 times — Narvan)

  • We have two queries that are unrelated to each other. How do you run these and combine their data? Do you run one first and then the other or how? (1 times — Snappshop)

  • How do you store money? (1 times — Visiwise)

    Answer

    Never use floating-point types (FLOAT, DOUBLE) for money. Use fixed-point precision:

    NUMERIC vs DECIMAL:

    DatabaseNUMERICDECIMALNotes
    PostgreSQLExact numeric typeAlias for NUMERICSame type, same behavior
    MySQLSynonym for DECIMALStandard SQL typeDECIMAL is preferred
    SQL ServerNot supportedStandard typeUse DECIMAL

    DECIMAL is the SQL standard; NUMERIC is PostgreSQL’s name for the same thing. Both store exact values with no rounding errors. Use DECIMAL for portability across databases.

    Storage for money:

    -- Prices and totals
    DECIMAL(12,2)    -- up to 999,999,999.99
    
    -- Exchange rates (higher precision)
    DECIMAL(18,8)    -- for crypto or FX rates
    
    -- Tax rates
    DECIMAL(5,2)     -- 0.00 to 999.99 percent
    

    In application code:

    from decimal import Decimal, ROUND_HALF_UP
    
    price = Decimal("19.99")
    tax = Decimal("0.0825")
    total = (price * (1 + tax)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
    # total = Decimal("21.64") ✅
    
    # ❌ Never do this
    total = 19.99 * 1.0825  # 21.6387025 — rounding nightmare
    

    Why not FLOAT/DOUBLE:

    0.1 + 0.2 == 0.3       # False!
    0.1 + 0.2               # 0.30000000000000004
    Decimal("0.1") + Decimal("0.2") == Decimal("0.3")  # True ✅
    

    Summary: Use DECIMAL (SQL standard) or NUMERIC (PostgreSQL). Never use FLOAT/DOUBLE for financial data. Always round at the display layer.

  • What is a dirty read? (1 times — 780)

    Answer

    A dirty read is a database error that happens when one transaction reads data changed by another transaction that has not finished or saved yet. If that first transaction cancels or rolls back its changes, the second transaction is left using data that never truly existed.

    • Transaction A changes a value (like lowering item count from 10 to 9) but does not commit/save yet.
    • Transaction B reads that new value (9) right before Transaction A finishes.
    • Transaction A encounters an error and rolls back, resetting the value back to 10.
    • Transaction B base their action on a false number (9), causing a dirty read error.

System Design

  • Microservices vs monolithic? How do you choose it when you want to start a project? (3 times — Snapp (cab 2), Snapp Market Pro, Tabdeal)

    Answer

    I usually start with a monolith and split it into microservices when needed. A monolith is faster to develop, easier to debug, and simpler to deploy and maintain, allowing the team to move quickly in the early stages. As the system grows and requirements such as independent scaling, team autonomy, or clear domain boundaries emerge, I gradually decompose it into microservices. This approach avoids the premature complexity of distributed systems—such as network communication, distributed transactions, and observability challenges—while keeping the architecture scalable.

  • What is event driven architecture? (1 times — Quiz of Kings)

  • We want to design a URL shortener system. How would you design it? (1 times — Quiz of Kings)

  • What is reverse proxy? (1 times — Autoshenas)

  • What would you do if suddenly we receive massive requests? How would you handle it? (1 times — Tabdeal)

  • For displaying a user’s daily Profit & Loss (P&L) in a crypto exchange system, which is more important: Consistency or Availability? Why? (1 times — Tabdeal)

  • What is double spending? (1 times — Tabdeal)

  • One service sent events to other service and retries it and we have 3 events in destination service how can handle it in second service? for example 3 same events of buy order. (1 times — Tabdeal)

  • How can we solve latency between our services in a microservices architecture? How can we protect against data loss? (1 times — Digikala)

  • What is consistency? (2 times — Doctoreto, Tabdeal)

    Answer

    In database systems (ACID), consistency (or correctness) refers to the requirement that any given database transaction must change affected data only in allowed ways. Any data written to the database must be valid according to all defined rules, including constraints, cascades, triggers, and any combination thereof. Wikipedia

    In CAP theorem: Every read receives the most recent write or an error. Consistency means that all clients see the same data at the same time, no matter which node they connect to. For this to happen, whenever data is written to one node, it must be instantly forwarded or replicated to all the other nodes in the system before the write is deemed ‘successful’ Wikipedia

  • What is a matching engine in an exchange? Explain how it works. (1 times — Netbox)

  • What is CAP theorem? (2 times — Snapp (cab 2), 780)

    Answer
  • How do you fix latency in microservices? (1 times — Snapp Market Pro)

  • Imagine a micro-services architecture. we want to follow up a request to have a track of them in the system. How do you suggest to track them. A: My Answer was to add a unique code in the header of the request (1 times — Toman Pay)

  • Writing and inserting data into the matching engine has become a bottleneck and slow for us. How can we solve this? (1 times — Wallex)

  • Suppose we have an e-commerce product (like Digikala) and there’s an issue: when I add one item to my basket, two are added. This happens sometimes. How would you fix this problem? (1 times — Wallgold)

    Answer
    1. Reproduce & observe

      Reproduce in dev with different browsers/devices and slow network.

      Capture request traces (client logs, server logs, request IDs, timestamps) and check analytics for patterns (specific browsers, mobile, retries).

    2. Identify likely causes

      Client: double-click, button not disabled, or UI retry/optimistic update doing a second call.

      Network/client library: automatic retry on timeout/resend.

      Server: non-idempotent endpoint creating two rows due to race conditions or missing uniqueness constraints.

      Message layer: duplicate messages processed twice.

    3. Fixes (short & practical)

      Client: disable add button after first click and debounce UI actions; show clear loading state.

      API: make the operation idempotent — accept an Idempotency-Key (or request id) and store processed keys to ignore duplicates.

      DB: enforce correctness with a uniqueness constraint on (cart_id, product_id) and use an atomic upsert to increment quantity, e.g.

  • We have two microservices. One of them is very slow and some requests time out without receiving a response. How can the other microservice handle this to avoid being affected? (1 times — Wallgold)

    Answer
    • Set a strict downstream timeout and propagate cancellation.

      • Use a circuit breaker to fail fast after repeated timeouts.

      • Retry only idempotent calls with exponential backoff + jitter (limit attempts).

      • Apply bulkheads (separate thread/connection pools) to isolate resources.

      • Provide fallbacks or cached responses where possible.

      • If suitable, make the call async (queue + worker) to decouple user latency.

      • Add metrics/tracing and alert on downstream latency/failure rates.

  • We have a very large, unstructured log file containing Divar chat data (ranging from gigabytes to terabytes). How would you approach detecting bot activity? (1 times — Wallgold)

    Answer
    1. Data Parsing and Structuring Reading File: To read a huge file efficiently, stream it in manageable chunks (e.g., several hundred MB at a time) instead of loading it all into memory. Use memory mapping for faster access when possible, and consider distributed or parallel processing frameworks like Apache Spark if you have large-scale infrastructure. Optimize I/O by tuning buffer sizes and, if applicable, store data in compressed or columnar formats to speed selective reads.

      Log Parsing: First, I’d parse the unstructured logs into a structured format (e.g., JSON or CSV) by extracting key fields such as timestamp, user ID, message content, IP address, and user agent (if available). This can be done using tools like Apache NiFi for data flow, or custom scripts with regular expressions, but for large-scale data, distributed processing is essential.

    2. Feature Engineering (Bot Indicators)

      Why: Bots exhibit patterns like bursty activity, repetition, and anomalies vs. human behavior. Key Features (Computed in Spark for scale):

      • Frequency: Messages per sender per hour/day (bots send 100x human rates).
      • Diversity: Unique receivers per sender (bots spam many).
      • Repetition: Message similarity (e.g., Jaccard or Levenshtein distance across a user’s messages).
      • Timing: Response latency (bots
  • What is middleware? (2 times — MH Holding, Toman Pay)

  • We have a system, and each time we receive an API request, imagine a user gets information. In the result, there are more data. How would you cache that? (1 times — Quiz of Kings)

  • What is DDD? (1 times — Autoshenas)

  • Which tools and mechanisms help keep a system consistent? (1 times — Doctoreto)

    Answer

    Common techniques: distributed consensus (Raft/Paxos), transactional guarantees (ACID), two-phase commit, idempotency + deduplication, transactional outbox and …

  • If you were given a project with slow loading performance, what steps would you take to improve it? (1 times — Kharazmi)

  • Suppose we used other service that has error how can handle it? (1 times — Hamkaran System)

  • In a microservices architecture, if service A depends on service B and a failure occurs mid-request (e.g., user balance is checked in A, then A calls B to deduct from the wallet, but B fails), how do you handle it? (1 times — Visiwise)

    Follow-up: Where does atomicity and rollback happen, and at what level do you solve this?

    Answer

    Where atomicity happens:

    Atomicity is per-service, not cross-service. Each service has its own local transaction. If A commits but B fails, A’s state is already written — you need a pattern to reconcile.

    Solutions by level:

    LevelPatternAtomicity Scope
    DatabaseLocal transactionsSingle service only
    MessagingTransactional OutboxGuarantees event delivery, not instant consistency
    SagaCompensation stepsLogical atomicity via rollback handlers
    APIRetry + idempotencyBest-effort, transient failure recovery

    Transactional Outbox (recommended):

    Service A:
    1. BEGIN TRANSACTION
       - INSERT into orders
       - INSERT into outbox (event: "deduct_wallet")
    2. COMMIT TRANSACTION (atomic — both succeed or both fail)
    3. Outbox poller → Kafka/RabbitMQ
    
    Service B:
    1. Consume message
    2. Idempotency check (event_id)
    3. BEGIN TRANSACTION
       - UPDATE wallet SET balance = balance - amount
       - INSERT into processed_events
    4. COMMIT TRANSACTION
    

    Failure recovery:

    Failure PointRecovery
    A’s DB commit failsFull rollback — no side effects
    A’s outbox poll failsEvent stays in outbox, retried
    B fails to processMessage retried by broker
    B processes twiceIdempotency check rejects duplicate

    Saga (for multi-step flows):

    Order Saga:
      Step 1: Create order      → compensation: cancel order
      Step 2: Deduct wallet     → compensation: refund wallet
      Step 3: Reserve inventory → compensation: release inventory
    
    If Step 3 fails:
      → refund wallet (Step 2 reverse)
      → cancel order (Step 1 reverse)
    

    Key takeaway: Atomicity in microservices is per-service (local DB transactions). Cross-service consistency is achieved through eventual consistency patterns (Saga, Outbox), not distributed transactions (2PC).

  • How do you update a user’s feed when they follow or unfollow someone? (1 times — Netbox)

  • Suppose we have sent a request to a service and an action failed. How can we handle other processes to know that the action has failed and handle them accordingly? (1 times — Ozone)

  • We have an API and we want to add new features on it. How can we handle compatibility with older version? v1 v2 (1 times — Snapp (cab 2))

  • How can we make sure that the codes you said, are unique? A: My answer was using UUID (1 times — Toman Pay)

  • Ok, we made the requests unique. Where can we store them? (1 times — Toman Pay)

  • Can you tell me the software layers that a request goes through in our code, and where it ends up? (1 times — Wallex)

  • Suppose we want to send 1 million notification and need request it to db how u handle it? (1 times — Wallex)

  • When do you use a cache? (1 times — Wallex)

  • Suppose we have a lot of requests and the number of our requests has increased. How do you handle this and manage it? (1 times — Wallex)

  • Think we know the problem is from front-end and we don’t want to deploy new version in front and want to fix it for short time in backend how fix it? (1 times — Wallgold)

    Answer
    1. Fast dedupe/lock in cache (Redis)

      Prevent processing the same “add” twice within a short window (2–5s). Build a dedupe key from stable request factors you have today (authenticated user_id or session_id, product_id, and a hash of the request body / headers). Use SET key value NX PX .

    2. Make DB operation idempotent/atomic (defensive)

      Even with Redis, races or Redis failures can happen. Enforce a DB-level uniqueness + atomic upsert so duplicates can’t create two rows.

    3. Optional: Consumer-side dedupe / idempotency store

      If your API is queue-based or background-processed, store processed request IDs (or the same dedupe key) for a short TTL and ignore duplicates.

    4. Response strategy & UX-friendly behavior

      When duplicate is detected in cache, return a harmless success (200) with current cart state — avoids confusing the frontend.

      If you detect duplicate after DB upsert, return the updated qty (so frontend can reconcile).

    5. Observability & short-term rollout

      Add logging/metric (count of dedupe-hits, Redis failures, db-constraint triggers).

      Feature-flag the change if possible; otherwise deploy in a safe rollout.

      Monitor for false positives (legitimate rapid adds being collapsed) and tune TTL (e.g., 2–5s).

    6. Caveats

      This is a short-term backend mitigation. It can merge legitimate rapid adds (user intentionally clicks twice quickly) — verify acceptable with product.

      Long-term: fix front-end (disable button/debounce + send idempotency key) for best UX.

  • How would you design a project for scale? What challenges might you face at scale? How would you design the data pipeline and scraper at scale? (1 times — Visiwise)

  • Design a mobile top-up system where users can purchase prepaid credit by entering their phone number and selecting a mobile operator. Assume each operator exposes a set of APIs for processing top-ups. Walk through your system design and the end-to-end request flow. (1 times — 780)

    Answer

    Step-by-step

    1. Create the transaction

    Status: pending


    2. Reserve the wallet balance

    • Don’t deduct it yet.
    • Move the amount from available to reserved.

    Status: FundsReserved


    3. Publish TopUpRequested

    The worker processes the request asynchronously.


    4. Call the operator

    If successful:

    • Capture the reservation (permanently deduct the funds).
    • Mark the transaction as Completed.

    If failed:

    • Release the reservation.
    • Mark the transaction as Failed.

    Why reserve instead of deduct immediately?

    Suppose the user has $10 and buys a $10 top-up.

    If you deduct immediately and the operator later returns an error, you must issue a refund, which introduces extra complexity and can fail.

    With reservations:

    • The money is temporarily locked.
    • It can’t be spent twice.
    • If the operator fails, you simply release the reservation.
    • If the operator succeeds, you capture it.

    This is the same pattern used by payment systems (authorization → capture).

  • We get an error when buying a top-up from a third-party operator, for example, a timeout. How would you handle this? (1 times — 780)

    Answer
    Reserve Funds
        │
        ▼
    Call Operator
        │
        ▼
    Timeout
    

    You should not immediately release the reservation because the operator may have successfully processed the top-up but failed to send a response.

    Instead:

    1. Mark the transaction as Pending.
    2. Retry or query the operator’s status API (or wait for a webhook if available).
    3. Only after receiving a definitive success or failure:
    • Capture the reservation on success.
    • Release the reservation on failure.

    This avoids both charging the user without delivering the top-up and giving away a free top-up. This pattern is commonly used in payment and financial systems to ensure consistency across distributed services.

Concurrency

  • What is race condition? (5 times — Quiz of Kings, Hamkaran System, Saraf, 2x Zibal)

    Answer

    A race condition happens when concurrent operations interleave and produce incorrect state. Solve it with mutual exclusion (mutexes) for in-process protection, transactions, locks (pessimistic or optimistic), atomic DB operations, idempotency, or by redesigning to avoid shared mutable state.

  • What is concurrency and parallelism? (4 times — Digikala, Hamkaran System, MH Holding, Siz-tel)

  • What is the difference between multithread and multiprocess? (2 times — Exalab, Snapp (cab 2))

  • What is the difference between multithreading and concurrency? (1 times — Snappshop)

  • What is the difference between a thread and a process? (1 times — Zibal)

    Answer

    Threads share a process memory space (lightweight, require synchronization). Processes have separate memory (safer isolation, heavier IPC). Choose threads for shared-memory, processes for isolation.

  • How can send data between processes? (1 times — Hamkaran System)

Networking

  • What is REST? (3 times — Autoshenas, Phanous, Wallex)

  • What does “stateless” mean in the context of REST? (2 times — Autoshenas, DAA)

  • How can link IP to domain in nginx? (2 times — Autoshenas, MH Holding)

  • Are there any APIs that are not stateless? (1 times — Autoshenas)

  • Valid parentheses (1 times — BitPin)

    Answer
        def check_braces(args: str)-> bool:
            dic = {'(':')', '[':']', '{':'}'}
            stack = []
            for s in args:
                if s in dic:
                    stack.append(s)
                elif stack == [] or dic[stack.pop()] != s:
                    return False
            return stack == []
    
  • Candy (1 times — BitPin)

    Answer
        def student_gift(nums: list):
            ans = [1] * len(nums)
            for i in range(len(nums)):
                for i in range(1, len(nums)):
                    if nums[i] > nums[i - 1]:
                        if ans[i] > ans[i -1]:
                            continue
                        else:
                            ans[i]+= 1
                    elif nums[i] < nums[i-1]:
                        if ans[i] < ans[i -1]:
                            continue
                        else:
                            ans[i-1]+=1
    
                for i in range(len(nums) - 1, 0, -1):
                    if nums[i] > nums[i - 1]:
                        if ans[i] > ans[i -1]:
                            continue
                        else:
                            ans[i]+= 1
                    elif nums[i] < nums[i-1]:
                        if ans[i] < ans[i -1]:
                            continue
                        else:
                            ans[i-1]+=1
    
            return ans
    
    
        students = [18, 14, 10,20]
        students2 = [i for i in range(1, 15)]
        students2.reverse()
        print("test case 1: ", students)
        result = student_gift(students)
        print("answer: ", result)
        print("test case 2: ", students2)
        result = student_gift(students2)
        print("answer: ", result)
    
  • What is restful? (1 times — DAA)

  • What is the difference between gRPC and REST? (1 times — Exalab)

  • Game theory question (pirate game) (1 times — Hermes Capital)

  • Tell me about http protocol. (2 times — 2x Karnameh)

  • What is difference between http and https? (1 times — Karnameh)

  • What is http1 and http2 differences? (1 times — Narvan)

  • When type google.com what’s happening? (1 times — Phanous)

  • What is difference between tcp & udp? (2 times — 2x Phanous)

  • What is OSI model? Say name of 7 layers. (1 times — Snapp (cab 1))

  • two sum (1 times — Yektanet)

Algorithms & Data Structures

  • What is hash collision and how do you resolve it? (2 times — Cloudzy, Hamkaran System)

    Answer
  • What is linked list? (2 times — Itoll, MH Holding)

  • What are the time complexities of search, insert, and delete in a linked list? (1 times — Cloudzy)

    Answer

    Search: O(n) Delete: O(1) Insert: O(1) - Big-O Cheatsheet

  • What is data structure behind map? (1 times — Hamkaran System)

  • Which one is better? linked list or array? (1 times — Itoll)

  • How can delete an item in linked list? (1 times — Itoll)

  • For delete, which one is faster? array or linked list? (1 times — Itoll)

  • What is fastest sorting algorithm? And what’s its time complexity? (1 times — Snapp (cab 1))

  • We want to implement a simple token-bucket algorithm in middleware to rate-limit users? (2 times — Saraf, Zibal)

    Answer

    Run

        package main
    
        import (
            "fmt"
            "time"
        )
    
        type User struct {
            accountID      int64
            capacity       int64
            counter        int64
            refillRate     int64
            lastRefillTime time.Time
        }
    
        func handler(user User, userData map[int64]User) {
            if _, ok := userData[user.accountID]; ok {
                fmt.Println("OK")
                ud := userData[user.accountID]
                if ud.counter >= ud.capacity {
                    fmt.Println(ud.counter)
                    panic("rate limit reached")
                }
                ud.counter++
                fmt.Println(ud.counter)
                elapsTime := time.Now().Unix() - ud.lastRefillTime.Unix()
                ud.counter += elapsTime * ud.refillRate
            } else {
                u := User{accountID: 123, capacity: 10, counter: 0, refillRate: 1}
                userData[u.accountID] = u
            }
            fmt.Println(user.counter, " ", user.capacity, " ", user.refillRate, " ", user.lastRefillTime)
        }
    
        func main() {
            userData := make(map[int64]User, 0)
            newUser := User{accountID: 123, capacity: 10, counter: 0, refillRate: 1, lastRefillTime: time.Now()}
            for i := range 10 {
                fmt.Println("i:", i)
                handler(newUser, userData)
            }
        }
    
  • First question (1 times — BitPin)

    Answer
        in_put = str(input())
        res = in_put.split()
        print(len(res[len(res) - 1]))
    
  • Second question (1 times — BitPin)

    Answer
        def check_2sum(nums: list, k: int) -> tuple | int:
            map_ = {}
            for i in range(len(nums)):
                map_[nums[i]] = i
    
            for i in range(len(nums)):
                target = k - nums[i]
                if target in map_ and map_[target] != i:
                    return i + 1, map_[target] + 1
    
            return -1
    
        n, target = map(int, input().split())
        nums = list(map(int, input().split()))
        res = check_2sum(nums, target)
    
        if res == -1:
            print(res)
        else:
            print(*res)
    
  • Third question (1 times — BitPin)

    Answer
        def longest_palindromic_subsequence(s: str) -> int:
        n = len(s)
        dp = [[0] * n for _ in range(n)]
    
        for i in range(n):
            dp[i][i] = 1
    
        for length in range(2, n + 1):
            for i in range(n - length + 1):
                j = i + length - 1
                if s[i] == s[j]:
                    if length == 2:
                        dp[i][j] = 2
                    else:
                        dp[i][j] = dp[i + 1][j - 1] + 2
                else:
                    dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
    
        return dp[0][n - 1]
    
        print(longest_palindromic_subsequence(input()))  # Output: 3 # Output: 5
    
  • We have this menu and there are task & subtasks. How you can traverse all items and access to each? (1 times — Sternx)

  • Math question: The market has reached a state where it has fallen 5 units, then after a while, it rises 1 unit, and this pattern has repeated. How can we predict the market for some time ahead (for example, a month)? How can we assess its probability? Do you have a solution? (1 times — Wallex)

  • Implement an LRU Cache in 20 mins. (1 times — Tabdeal)

    Answer (My solution)
    class LRUCache:
        def __init__(self, capacity: int) -> None:
            self.capacity = capacity
            self.cache = {}
            
        def put(self, key: int, value: int):
            if key in self.cache:
                self.cache[key] = value
                self.cache[key] = self.cache.pop(key)
            else:
                if len(self.cache) == self.capacity:
                    del self.cache[next(iter(self.cache))]
                self.cache[key] = value
    
        def get(self, key: int):
            if key not in self.cache:
                return -1
            self.cache[key] = self.cache.pop(key)
            return self.cache[key]
    
        def print_cache(self):
            print(self.cache)
    
    c = LRUCache(3)
    
    c.put(1,1)
    c.put(2,2)
    c.put(3,3)
    c.print_cache()
    c.get(2)
    c.get(1)
    c.print_cache()
    c.put(4,4)
    c.print_cache()
    
  • You have n files (txt) and we want to remove duplicate files. How do you do it? (1 times — 780)

    Answer

    Part 1: Standard Scenario (Sufficient RAM)

    When you have enough RAM, the primary goal is speed. We can leverage in-memory data structures to avoid unnecessary disk I/O.

    The Algorithm

    1. Filter by Size: Iterate through all n files and group them by their file size. If two files have different sizes, they absolutely cannot be duplicates. This eliminates the vast majority of files instantly with zero file-content reading.
    2. Hash the Content: For files that share the same size, read their contents and calculate a cryptographic hash (e.g., SHA-256).
    3. Use a Hash Map: Use an in-memory dictionary/hash map where the Key is the SHA-256 hash and the Value is a list of file paths.
    4. Resolve Duplicates:
      • If you compute a hash and it’s not in the map, add it.
      • If the hash is already in the map, append the current file path to the value list.
    5. Delete: Iterate through your hash map. For every key that has more than one file path in its list, keep the first file and delete the rest.

    Complexity

    • Time Complexity: O(N) where N is the total number of bytes across all files.
    • Space Complexity: O(U) where U is the number of unique files (required to store the hash map and active file handles).
  • OK, you don’t have enough RAM to read the files; you only have 20KB of RAM. What would you do? (1 times — 780)

    Answer

    Part 2: Constrained Scenario (Only 20KB RAM)

    20KB of RAM is extremely restrictive. You cannot hold a standard hash map, nor can you hold a large list of file paths (a 100-character path string for 200 files already exceeds 20KB).

    You must rely entirely on External Sorting and Streaming (Chunking). This approach is similar to how classic Unix tools like fdupes operate under the hood, heavily optimized for disk rather than RAM.

    Step 1: Group by Size using Disk

    Since you cannot hold a map of size -> [files] in RAM, you offload this grouping to disk.

    1. Create a temporary text file (sizes.txt).
    2. Read the directory. For each file, append FileSize|FilePath\n to sizes.txt. (This takes almost zero RAM).
    3. Use an External Sort (e.g., a disk-based merge sort) to sort sizes.txt numerically by the file size. Note: External sort only requires small sequential reads/writes of chunks into your 20KB RAM buffer.
    4. Iterate through the sorted sizes.txt sequentially. Any file with a unique size is immediately marked as “Keep”. Group the paths of files with identical sizes into temporary “candidate lists” on disk.

    Step 2: Progressive Chunking (No Hashing)

    Why no hashing in this scenario? To hash a file, you must process every single byte of the file. If two 10GB files differ in the very first byte, reading and hashing the remaining 10GB is a massive waste of disk I/O.

    Instead, compare the candidate files byte-by-byte in small chunks that fit inside your 20KB RAM limit.

    Assume you have a group of 5 candidate files that are all exactly 1,000,000 bytes long:

    1. Open all 5 file handles simultaneously.
    2. Allocate a small read buffer in your RAM (e.g., a 2KB character array).
    3. Read the first 2KB from File 1 into Buffer A.
    4. Read the first 2KB from File 2 into Buffer B and compare them.
      • If they differ: Close File 2. It is unique. Remove it from the candidate group.
      • If they match: Discard Buffer B, read File 3 into Buffer B, compare against Buffer A, and so on.
    5. RAM Check: Comparing 5 files requires holding one 2KB “master” buffer and one 2KB “comparison” buffer at a time (4KB total). This easily fits in 20KB. (If the candidate group is massive, you might have to compare in sub-groups, but typically, groups of identical sizes are small).
    6. Once you have compared the first 2KB of all candidates, discard the buffers, advance the file pointers, and repeat the process for the next 2KB chunk.
    7. If you reach the End of File (EOF) and multiple files have matched perfectly across all chunks, they are exact duplicates.

    Step 3: Delete

    Keep the first file in the fully matched group, and issue OS-level delete commands for the rest.

  • We have a file with a lot of names. How do you remove duplicate names? (1 times — 780)

    Answer

    In-memory: Stream the file, use a hash set to track seen names, write only first occurrences — O(n) time, O(unique names) memory. In go we can use map.

  • Right! If we don’t want to use memory, how do we solve it? (1 times — 780)

    Answer

    We just must use O(n^2) loop.

DevOps & Infrastructure

  • What is docker & kubernetes? (6 times — Quiz of Kings, 2x Autoshenas, Phanous, Snapp (cab 2), Snappshop)

  • What is the difference between virtual machine and docker? (2 times — Snapp (cab 2), Snappshop)

  • What is EXPOSE in docker? (1 times — Autoshenas)

  • Can you build up a project with docker? (1 times — Autoshenas)

  • What is image in docker? (1 times — MH Holding)

  • What is systemD? (1 times — Narvan)

  • How network models in docker? (1 times — Narvan)

  • What features does Linux have that Docker uses for isolated and separate operating systems and for running multiple isolated operating systems? (1 times — Snappshop)

  • How can we know capacity of disk or directory? what command? (1 times — Narvan)

  • What is CI and CD? and the differences? (1 times — Snapp (cab 2))

  • The pod is not down, but you have an error (for example, error 500). How do you know where it comes from? (1 times — Snappshop)

  • How do you determine if an application is slow, and how do you measure it? (1 times — Snappshop)

Message Brokers & Queues

  • What is event sourcing and CQRS? (1 times — Autoshenas)

  • When do you use queue? (1 times — Tabdeal)

  • When do you use kafka? (1 times — Exalab)

  • What is partition in kafka? (1 times — Exalab)

  • We have two consumers and there are a hundred messages in the queue (RabbitMQ). The first one takes all of them. What should we do so that the second one also receives some? (1 times — Snappshop)

  • What if Our RabbitMQ or Celery Fails? What is your solution not too lose any of the tracking data? (1 times — Toman Pay)

  • What mechanisms do you use to make message processing resilient? (1 times — Doctoreto)

    Answer

    Transactional outbox

  • How to know how many queues do we need? (I didn’t know the answer!) (1 times — Toman Pay)

Testing

  • You mentioned using BDD, how do you write BDD-style tests? (1 times — Cloudzy)

  • You wrote: “I used Test-Driven Development (TDD) to write tests for critical components, ensuring functional accuracy and improving code quality.” How do tests improve code quality? (1 times — Netbox)

  • Is TDD OK? If I say we don’t need to write tests, what’s your reaction in a team? (1 times — Wallex)

  • You mentioned a simulator bot on your resume. How do you use it to test features and load? (The simulator bot acts like real users to validate functionality and performance.) (1 times — Netbox)

  • Is writing tests good or bad, since there usually isn’t enough time to write them? What’s your opinion? (1 times — Netbox)

Git

  • What is git rebase? (2 times — Sternx, Wallex)

  • What is gitflow and workflow? (1 times — Siz-tel)

  • How you fix merge conflict? (1 times — Snappshop)

  • What is difference between git Merge and Rebase? (1 times — Snappshop)

  • What is fast-forward? (1 times — Snappshop)

  • How do you push commits to another branch? (1 times — Zibal)

    Answer

    cherry-pick

Security & Cryptography

  • What is difference between Authentication and Authorization? (1 times — DAA)

  • Someone tries to login our system with brute force approach. What’s your solution to deal with this problem? (1 times — Phanous)

  • What is the difference between hashing and encryption? (1 times — Snappshop)

  • What is difference between RSA and AES? (1 times — Snappshop)

  • What hashing algorithm do you use? (1 times — Snappshop)

  • When we want to know a user authenticated or not for some action, how know that and how we handle that? (1 times — Wallex)

Design Patterns & SOLID

  • What is SOLID? (5 times — Digikala, Itoll, Kharazmi, Snapp (cab 2), Wallex)

  • What is polymorphism? (2 times — Itoll, Snapp (cab 1))

  • What is MVC? (1 times — Digikala)

  • Which part of MVT that we working with data? (1 times — Digikala)

  • What is singleton? (1 times — Digikala)

  • What is dependency inversion? (3 times — 3x Wallex)

  • What is object pool? (1 times — Digikala)

  • What is a design pattern, and which design patterns have you used? (7 times — Digikala, Exalab, Itoll, MH Holding, Snapp (cab 1), Sternx, Wallex)

  • What is DI? (2 times — Digikala, Zibal)

    Answer

    Dependency injection supplies an object’s dependencies from the outside (constructor, setter, or factory) rather than creating them internally; this improves testability, decoupling, and configurability.

  • Why do we use a repository layer in a service? (1 times — Zibal)

    Answer

    A repository abstracts persistence, centralizes queries, and decouples domain logic from storage details — making testing, swapping databases, and enforcing consistency simpler.

OOP

  • What is abstract class? (1 times — Itoll)

  • What is access modifiers? (1 times — Snapp (cab 1))

  • What is interface? (3 times — Itoll, MH Holding, Siz-tel)

  • How can create private methods? (1 times — Digikala)

  • What is data binding? How many types does it have? (1 times — Kharazmi)

  • What is update method? (1 times — Karnameh)

  • Write a base class in C++ that name is Animal then create two child classes of it like Dog and Cat and each of these have Eat method but Eat is different in Dog and Cat. And we create some instance of these classes and put them into an array. How can we do that? What is the type of this array? (1 times — Snapp (cab 1))

gRPC & Communication

  • What are the main benefits of gRPC? (2 times — Doctoreto, Narvan)

    Answer

    High performance (HTTP/2 multiplexing), low latency, built-in streaming (client/server/bi-directional), strongly typed contracts via protobuf and code generation, language polyglot support, and built-in interception hooks (auth, load–balancing). Good for microservices and low-latency RPCs.

  • What is RPC? (1 times — Digikala)

Misc

  • When you prefer use other packages or write your library? (2 times — 2x Autoshenas)
  • What is signal? (1 times — Kharazmi)
  • What is eventEmitter? (1 times — Kharazmi)
  • What are guards in Angular? where have you used them? (1 times — Kharazmi)
  • What is Angular optimization? (1 times — Kharazmi)
  • Have you ever had a weird bug in production even though all your tests passed? How did you fix it? (1 times — Football360)
  • We have 2 mindsets in software engineering. One is “tools, languages and stack is not important, you should solve problems regardless of tools.” and the other one is “tools is important and everyone have to solve problems with tools that know them”. Which mindset do you prefer? (1 times — Ozone)