# Replication and Event Loop

**URL:** <https://forum.codecrafters.io/t/replication-and-event-loop/1664>\
**Category:** Challenges\
**Tags:** challenge:redis\
**Created:** [September 8, 2024, 9:05pm UTC](https://forum.codecrafters.io/t/replication-and-event-loop/1664 "2024-09-08T21:05:23Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![TobiasKrok](https://yyz1.discourse-cdn.com/flex003/user_avatar/forum.codecrafters.io/tobiaskrok/32/1572_2.png) [@TobiasKrok](https://forum.codecrafters.io/u/TobiasKrok)\
**Post date:** [September 8, 2024, 9:05pm UTC](https://forum.codecrafters.io/t/replication-and-event-loop/1664/1 "2024-09-08T21:05:23Z")

</div>

Hey!

I am a bit stuck on handling replication for Redis at stage #gl7. I\m trying to use an event loop with Java NIO but I am struggling with figuring out how the replica can both handle messages and connect to the master without spawning a new thread and creating a separate event loop there.

My EventLoop looks like this:

```java
package core;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

class EventLoop {

private final RedisCommandHandler commandHandler;
    public EventLoop(RedisCommandHandler commandHandler) {
        this.commandHandler = commandHandler;
    }
    private boolean stop = false;

    protected void run(int port) throws IOException {
        try (ServerSocketChannel ssc = ServerSocketChannel.open()) {
            ssc.bind(new InetSocketAddress("localhost", port));
            ssc.configureBlocking(false);
            Selector selector = Selector.open();
            ssc.register(selector, SelectionKey.OP_ACCEPT);

            while (!stop) {
                selector.select();
                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
                while (keyIterator.hasNext()) {
                    SelectionKey key = keyIterator.next();
                    if (key.isAcceptable()) {
                        // accpets a new client and say that we're interested in reading from that client
                        ServerSocketChannel server = (ServerSocketChannel) key.channel();
                        SocketChannel client = server.accept();
                        client.configureBlocking(false);
                        client.register(selector, SelectionKey.OP_READ);
                        System.out.println("redis: registered client " + client.getRemoteAddress());
                    } else if (key.isReadable()) {
                        // we got some data from a client that we are interested in and now we read
                        SocketChannel client = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(256);
                        int bytesRead = client.read(buffer);
                        System.out.printf("redis: recv %s bytes from client " + client.getRemoteAddress() + "%n", bytesRead);
                        if (bytesRead == -1) {
                            client.close();
                        } else {
                            buffer.flip();
                           List<String> rawCommands = RespParser.read(buffer);
                           byte[] res = commandHandler.process(rawCommands);
                            client.write(ByteBuffer.wrap(res));
                        }

                    }
                    keyIterator.remove();
                }
            }
        }
    }
}

```

How would you suggest handling connecting to the master as a replica while still running the event loop to handle messages?

Here is my GitHub link: [GitHub - TobiasKrok/redis: redis challenge from Codecrafters](https://github.com/TobiasKrok/redis)  
Thank you!

---

<div class="post-metadata">

**Author:** ![andy1li](https://yyz1.discourse-cdn.com/flex003/user_avatar/forum.codecrafters.io/andy1li/32/10_2.png) [@andy1li](https://forum.codecrafters.io/u/andy1li)\
**Post date:** [September 9, 2024, 6:02am UTC](https://forum.codecrafters.io/t/replication-and-event-loop/1664/2 "2024-09-09T06:02:58Z")

</div>

> How would you suggest handling connecting to the master as a replica while still running the event loop to handle messages?

To pass this stage, try to complete the handshake **before** starting the event loop.

> I am struggling with figuring out how the replica can both handle messages and connect to the master without spawning a new thread and creating a separate event loop there.

Yes, you’ll eventually need to juggle both, but you’ll in a better position to tackle the problem once you have more completed stages under your belt.

---

<div class="post-metadata">

**Author:** ![TobiasKrok](https://yyz1.discourse-cdn.com/flex003/user_avatar/forum.codecrafters.io/tobiaskrok/32/1572_2.png) [@TobiasKrok](https://forum.codecrafters.io/u/TobiasKrok)\
**Post date:** [September 9, 2024, 6:49am UTC](https://forum.codecrafters.io/t/replication-and-event-loop/1664/3 "2024-09-09T06:49:17Z")

</div>

Fair enough, I will try that before worrying about the rest!

> [@andy1li](#):
>
> Yes, you’ll eventually need to juggle both, but you’ll in a better position to tackle the problem once you have more completed stages under your belt.

Do you happen to know how Redis handles it in its event loop? Does it handle replication in a separate process?

Thank you for your help!

---

<div class="post-metadata">

**Author:** ![andy1li](https://yyz1.discourse-cdn.com/flex003/user_avatar/forum.codecrafters.io/andy1li/32/10_2.png) [@andy1li](https://forum.codecrafters.io/u/andy1li)\
**Post date:** [September 9, 2024, 7:04am UTC](https://forum.codecrafters.io/t/replication-and-event-loop/1664/4 "2024-09-09T07:04:49Z")

</div>

TBH, I haven’t delved into how the official Redis works in this particular area. But we do have a code walkthrough about [How the Redis event loop is implemented](https://app.codecrafters.io/walkthroughs/redis-event-loop).

My implementation in Python used a non-blocking Task (coroutine). I believe Java has something similar too.

---

<div class="post-metadata">

**Author:** ![TobiasKrok](https://yyz1.discourse-cdn.com/flex003/user_avatar/forum.codecrafters.io/tobiaskrok/32/1572_2.png) [@TobiasKrok](https://forum.codecrafters.io/u/TobiasKrok)\
**Post date:** [September 9, 2024, 7:12am UTC](https://forum.codecrafters.io/t/replication-and-event-loop/1664/5 "2024-09-09T07:12:33Z")

</div>

I see, I’ll have to investigate the event loop implementation a bit more! Might just have to spawn a separate thread.

Thank you!

---

<div class="post-metadata">

**Author:** ![system](https://canada1.discourse-cdn.com/flex003/uploads/codecrafters/original/3X/7/0/700657133935c15703e22c7c8870394f6e6dc27d.svg) [@system](https://forum.codecrafters.io/u/system)\
**Post date:** [September 14, 2024, 7:13am UTC](https://forum.codecrafters.io/t/replication-and-event-loop/1664/6 "2024-09-14T07:13:19Z")

</div>

Closed on September 14, 2024, 7:13am UTC

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.
